android.app.Activity Java Examples

The following examples show how to use android.app.Activity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppLinkData.java    From Klyph with MIT License 7 votes vote down vote up
/**
 * Parses out any app link data from the Intent of the Activity passed in.
 * @param activity Activity that was started because of an app link
 * @return AppLinkData if found. null if not.
 */
public static AppLinkData createFromActivity(Activity activity) {
    Validate.notNull(activity, "activity");
    Intent intent = activity.getIntent();
    if (intent == null) {
        return null;
    }

    String appLinkArgsJsonString = intent.getStringExtra(BUNDLE_APPLINK_ARGS_KEY);
    // Try v2 app linking first
    AppLinkData appLinkData = createFromJson(appLinkArgsJsonString);
    if (appLinkData == null) {
        // Try regular app linking
        appLinkData = createFromUri(intent.getData());
    }

    return appLinkData;
}
 
Example #2
Source File: DialogsMaintainer.java    From DialogUtil with Apache License 2.0 6 votes vote down vote up
public static void dismissLoading(Activity activity) {

        if (activity == null) {
            return;
        }
        if (!loadingDialogs.containsKey(activity)) {
            return;
        }
        Set<Dialog> dialogSet = loadingDialogs.get(activity);
        for (Dialog dialog : dialogSet) {
            dialog.dismiss();
            //在callback内部自动会去移除在dialogsOfActivity的引用
        }
        loadingDialogs.remove(activity);

    }
 
Example #3
Source File: EipFragment.java    From bitmask_android with GNU General Public License v3.0 6 votes vote down vote up
private void showToast(Activity activity, String message, boolean vibrateLong) {
    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.custom_toast,
            activity.findViewById(R.id.custom_toast_container));

    TextView text = layout.findViewById(R.id.text);
    text.setText(message);

    Vibrator v = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
    if (vibrateLong) {
        v.vibrate(100);
        v.vibrate(200);
    } else {
        v.vibrate(100);
    }

    Toast toast = new Toast(activity.getApplicationContext());
    toast.setGravity(Gravity.BOTTOM, 0, convertDimensionToPx(this.getContext(), R.dimen.stdpadding));
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();
}
 
Example #4
Source File: TelephoneUtil.java    From AndroidBase with Apache License 2.0 6 votes vote down vote up
/**
 * 获取设备唯一ID
 * 先以IMEI为准,如果IMEI为空,则androidId
 * 下次使用deviceId的时候优先从外部存储读取,再从背部存储读取,最后在重新生成,尽可能的保证其不变性
 *
 * @param activity
 * @return
 */
public static Observable<String> getDeviceId(final Activity activity) {
   return new RxPermissions(activity)
            .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
            .flatMap(new Function<Boolean, ObservableSource<String>>() {
                @Override
                public ObservableSource<String> apply(Boolean granted) throws Exception {
                    String path = null;
                    if (granted) {
                        path = getExternalStoragePath();
                    }

                    if (Check.isEmpty(path)) {
                        path = getPath();
                    }
                    String deviceId = readAndWriteDeviceId(activity, path);
                    return Observable.just(deviceId);
                }
            });
}
 
Example #5
Source File: SlideAdapter.java    From Coloring-book with Apache License 2.0 6 votes vote down vote up
public SlideAdapter(Activity activity, String packName) {

        Display display = activity.getWindowManager().getDefaultDisplay();
        height = display.getHeight();  // deprecated
        height = (height / 5) * 3;

        prefs = activity.getSharedPreferences("com.bublecat.drawer", Activity.MODE_PRIVATE);
        String levels = prefs.getString(packName, null);
        levelsList = new ArrayList<Integer>();
        if (levels != null) {
            String[] everyLevel = levels.split(",");
            for (int i = 0; i < everyLevel.length; i++) {
                int lv = Integer.parseInt(everyLevel[i]);
                levelsList.add(lv);
            }
        }
        this.activity = activity;
        this.packName = packName;
    }
 
Example #6
Source File: EntityDetailView.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("AddJavascriptInterface")
private void addSpinnerToGraph(WebView graphView, ViewGroup graphLayout) {
    // WebView.addJavascriptInterface should not be called with minSdkVersion < 17
    // for security reasons: JavaScript can use reflection to manipulate application
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        return;
    }

    final ProgressBar spinner = new ProgressBar(this.getContext(), null, android.R.attr.progressBarStyleLarge);
    spinner.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
    GraphLoader graphLoader = new GraphLoader((Activity)this.getContext(), spinner);

    // Set up interface that JavaScript will call to hide the spinner
    // once the graph has finished rendering.
    graphView.addJavascriptInterface(graphLoader, "Android");

    // The above JavaScript interface doesn't load properly 100% of the time.
    // Worst case, hide the spinner after ten seconds.
    Timer spinnerTimer = new Timer();
    spinnerTimer.schedule(graphLoader, 10000);
    graphLayout.addView(spinner);
}
 
Example #7
Source File: PreferenceUtil.java    From apollo-DuerOS with Apache License 2.0 6 votes vote down vote up
public void init(final Context context) {
    if (context == null) {
        return;
    }
    mPreferences = context.getSharedPreferences(CommonParams.CARLIFE_NORMAL_PREFERENCES,
            Activity.MODE_PRIVATE);
    mEditor = mPreferences.edit();

    Context carlifeContext = null;
    try {
        carlifeContext = context.createPackageContext(context.getPackageName(),
                Context.CONTEXT_IGNORE_SECURITY);
        mJarPreferences = carlifeContext.getSharedPreferences(
                CommonParams.CONNECT_STATUS_SHARED_PREFERENCES, Context.MODE_WORLD_WRITEABLE
                        | Context.MODE_WORLD_READABLE | Context.MODE_MULTI_PROCESS);
        mJarEditor = mJarPreferences.edit();
    } catch (Exception e) {
        LogUtil.e(TAG, "init jar sp fail");
        e.printStackTrace();
    }
}
 
Example #8
Source File: RunningActivities.java    From DroidPlugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void onActivtyDestory(Activity activity) {
    synchronized (mRunningActivityList) {
        RunningActivityRecord value = mRunningActivityList.remove(activity);
        if (value != null) {
            ActivityInfo targetActivityInfo = value.targetActivityInfo;
            if (targetActivityInfo.launchMode == ActivityInfo.LAUNCH_MULTIPLE) {
                mRunningSingleStandardActivityList.remove(value.index);
            } else if (targetActivityInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
                mRunningSingleTopActivityList.remove(value.index);
            } else if (targetActivityInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
                mRunningSingleTaskActivityList.remove(value.index);
            } else if (targetActivityInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
                mRunningSingleInstanceActivityList.remove(value.index);
            }
        }
    }
}
 
Example #9
Source File: TImageFiles.java    From TakePhoto with Apache License 2.0 6 votes vote down vote up
/**
 * To find out the extension of required object in given uri
 * Solution by http://stackoverflow.com/a/36514823/1171484
 */
public static String getMimeType(Activity context, Uri uri) {
    String extension;
    //Check uri format to avoid null
    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        //If scheme is a content
        extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(context.getContentResolver().getType(uri));
        if (TextUtils.isEmpty(extension)) {
            extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
        }
    } else {
        //If scheme is a File
        //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file
        // name with spaces and special characters.
        extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
        if (TextUtils.isEmpty(extension)) {
            extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(context.getContentResolver().getType(uri));
        }
    }
    if (TextUtils.isEmpty(extension)) {
        extension = getMimeTypeByFileName(TUriParse.getFileWithUri(uri, context).getName());
    }
    return extension;
}
 
Example #10
Source File: LayerManager.java    From google-media-framework-android with Apache License 2.0 6 votes vote down vote up
/**
 * Given a container, create the video layers and add them to the container.
 * @param activity The activity which will display the video player.
 * @param container The frame layout which will contain the views.
 * @param video the video that will be played by this LayerManager.
 * @param layers The layers which should be displayed on top of the container.
 */
public LayerManager(Activity activity,
                    FrameLayout container,
                    Video video,
                    List<Layer> layers) {
  this.activity = activity;
  this.container = container;
  container.setBackgroundColor(Color.BLACK);

  ExoplayerWrapper.RendererBuilder rendererBuilder =
      RendererBuilderFactory.createRendererBuilder(activity, video);

  exoplayerWrapper = new ExoplayerWrapper(rendererBuilder);
  exoplayerWrapper.prepare();

  this.control = exoplayerWrapper.getPlayerControl();

  // Put the layers into the container.
  container.removeAllViews();
  for (Layer layer : layers) {
    container.addView(layer.createView(this));
    layer.onLayerDisplayed(this);
  }
}
 
Example #11
Source File: PermissionHelper.java    From MissZzzReader with Apache License 2.0 6 votes vote down vote up
/**
 * 声音设备权限
 * @param context
 * @return
 */
public static boolean isAudioPermission(Context context) {
    boolean permission = false;
    if (Build.VERSION.SDK_INT >= 23) {
        int checkReadPhoneStatePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO);
        if (checkReadPhoneStatePermission != PackageManager.PERMISSION_GRANTED) {
            // 弹出对话框接收权限
            ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.RECORD_AUDIO}, 1);
            TextHelper.showText("当前应用未拥有音频录制权限");
        } else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            // 弹出对话框接收权限
            ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.RECORD_AUDIO}, 1);
            TextHelper.showText("当前应用未拥有音频录制权限");
        } else {
            permission = true;
        }
    } else {
        permission = true;
    }
    return permission;
}
 
Example #12
Source File: ScreenUtils.java    From BookReader with Apache License 2.0 6 votes vote down vote up
/**
 * 调整窗口的透明度  1.0f,0.5f 变暗
 *
 * @param from    from>=0&&from<=1.0f
 * @param to      to>=0&&to<=1.0f
 * @param context 当前的activity
 */
public static void dimBackground(final float from, final float to, Activity context) {
    final Window window = context.getWindow();
    ValueAnimator valueAnimator = ValueAnimator.ofFloat(from, to);
    valueAnimator.setDuration(500);
    valueAnimator.addUpdateListener(
            new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    WindowManager.LayoutParams params = window.getAttributes();
                    params.alpha = (Float) animation.getAnimatedValue();
                    window.setAttributes(params);
                }
            });
    valueAnimator.start();
}
 
Example #13
Source File: PermissiomUtilNew.java    From Android with MIT License 6 votes vote down vote up
/**
 * Version 6.0 to determine whether a camera available before (now mainly rely on the try... catch... catch exceptions)
 * @param activity
 * @return
 */
private boolean checkCamera(Activity activity) {
    boolean canUse = true;
    Camera mCamera = null;
    try {
        mCamera = Camera.open();
        Camera.Parameters mParameters = mCamera.getParameters();
        mCamera.setParameters(mParameters);
    } catch (Exception e) {
        canUse = false;
    }
    if (mCamera != null) {
        mCamera.release();
    }
    if(!canUse){
        showDialog(activity,Manifest.permission.CAMERA);
    }
    return canUse;
}
 
Example #14
Source File: UpdateToastMediaScannerCompletionListener.java    From Orin with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onScanCompleted(final String path, final Uri uri) {
    Activity activity = activityWeakReference.get();
    if (activity != null) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast toast = toastWeakReference.get();
                if (toast != null) {
                    if (uri == null) {
                        failed++;
                    } else {
                        scanned++;
                    }
                    String text = " " + String.format(scannedFiles, scanned, toBeScanned.length) + (failed > 0 ? " " + String.format(couldNotScanFiles, failed) : "");
                    toast.setText(text);
                    toast.show();
                }
            }
        });
    }
}
 
Example #15
Source File: AppManager.java    From MVPFrame with MIT License 5 votes vote down vote up
public Activity beforeActivity() {
    Activity activity = null;
    if (mActivityStack.size() > 1) {
        activity = mActivityStack.get(mActivityStack.size() - 2);
    }
    return activity;
}
 
Example #16
Source File: Navigator.java    From Pioneer with Apache License 2.0 5 votes vote down vote up
/**
     * 启动主界面,可在Splash界面或出现异常时使用.
     * @param context
     */
    public static void launchMain(Context context) {
//        context.getPackageManager().resolveActivity(
//                new Intent(Intent.ACTION_MAIN).setPackage(context.getPackageName())
//                        .addCategory(Intent.CATEGORY_DEFAULT),
//                0);
        boolean inActivityContext = context instanceof Activity;
        Intent intent = new Intent(context, MainActivity.class);
        if (!inActivityContext) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (context instanceof MainActivity) {
            ((MainActivity) context).close();
        }
        context.startActivity(intent);
        if (context instanceof Activity) {
            if (context instanceof SplashActivity)
                ((Activity) context).overridePendingTransition(android.R.anim.fade_in, 0);
            ((Activity) context).overridePendingTransition(0, 0);
        }
        if (context instanceof Activity && !(context instanceof MainActivity)) {
            ActivityCompat.finishAffinity((Activity) context);
            ((Activity) context).overridePendingTransition(0, android.R.anim.fade_out);
        }
    }
 
Example #17
Source File: ActivityIabHelperImpl.java    From OPFIab with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
protected Activity getActivity() {
    if (fragmentActivity != null) {
        return fragmentActivity;
    }
    if (activity != null) {
        return activity;
    }

    throw new IllegalStateException();
}
 
Example #18
Source File: TencentMapLiteActivity.java    From XposedWechatHelper with GNU General Public License v2.0 5 votes vote down vote up
public static void actionStart(Activity context,
                               String lat, String lon) {
    Intent intent = new Intent(context, TencentMapLiteActivity.class);
    intent.putExtra(TencentMapLiteActivity.LAT_KEY, lat);
    intent.putExtra(TencentMapLiteActivity.LON_KEY, lon);
    context.startActivityForResult(intent, REQUEST_CODE);
}
 
Example #19
Source File: EaseChatRow.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
public EaseChatRow(Context context, EMMessage message, int position, BaseAdapter adapter) {
    super(context);
    this.context = context;
    this.activity = (Activity) context;
    this.message = message;
    this.position = position;
    this.adapter = adapter;
    inflater = LayoutInflater.from(context);

    initView();
}
 
Example #20
Source File: FilterRulesFragment.java    From NekoSMS with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
        return;
    }

    if (requestCode == IMPORT_BACKUP_REQUEST) {
        showConfirmImportDialog(data.getData());
    } else if (requestCode == EXPORT_BACKUP_REQUEST) {
        exportFilterRules(data.getData());
    }
}
 
Example #21
Source File: CreditCardFragment.java    From CreditCardView with MIT License 5 votes vote down vote up
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    if (activity instanceof ActionOnPayListener) {
        actionOnPayListener = (ActionOnPayListener) activity;
    }

}
 
Example #22
Source File: ActivityProxy.java    From GPT with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onTouchEvent(MotionEvent event) {
    Activity target = getCurrentActivity();
    if (target != null) {
        return target.onTouchEvent(event);
    } else {
        return super.onTouchEvent(event);
    }
}
 
Example #23
Source File: NfcTagSkillViewFragment.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQCODE_WAIT_FOR_TAG && resultCode == Activity.RESULT_OK) {
        Logger.d("got expected result. setting data");
        byte[] tag_id = data.getByteArrayExtra(WaitForNfcActivity.EXTRA_ID);
        editText.setText(NfcTagEventData.byteArray2hexString(tag_id));
    }
}
 
Example #24
Source File: WhitelistFragment.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Shows a popup on the screen of Android device.
 * 
 * @param text the text message.
 */
private void showPopup(final String text) {
    final Activity activity = getActivity();
    if (activity == null) {
        return;
    }
    activity.runOnUiThread(() -> {
        Toast.makeText(activity, text, Toast.LENGTH_LONG).show();
    });
}
 
Example #25
Source File: SdkPermissionsManager.java    From RePlugin-GameSdk with Apache License 2.0 5 votes vote down vote up
@TargetApi(11)
private Activity getActivity(Object object) {
    if (object instanceof Activity) {
        return ((Activity) object);
    } else if (object instanceof Fragment) {
        return ((Fragment) object).getActivity();
    } else if (object instanceof android.app.Fragment) {
        return ((android.app.Fragment) object).getActivity();
    } else {
        return null;
    }
}
 
Example #26
Source File: PlacePickerFragment.java    From Abelana-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
    super.onInflate(activity, attrs, savedInstanceState);
    TypedArray a = activity.obtainStyledAttributes(attrs, R.styleable.com_facebook_place_picker_fragment);

    setRadiusInMeters(a.getInt(R.styleable.com_facebook_place_picker_fragment_radius_in_meters, radiusInMeters));
    setResultsLimit(a.getInt(R.styleable.com_facebook_place_picker_fragment_results_limit, resultsLimit));
    if (a.hasValue(R.styleable.com_facebook_place_picker_fragment_results_limit)) {
        setSearchText(a.getString(R.styleable.com_facebook_place_picker_fragment_search_text));
    }
    showSearchBox = a.getBoolean(R.styleable.com_facebook_place_picker_fragment_show_search_box, showSearchBox);

    a.recycle();
}
 
Example #27
Source File: AppManager.java    From HttpRequest with Apache License 2.0 5 votes vote down vote up
/**
 * 添加Activity到堆栈
 * @author leibing
 * @createTime 2016/10/14
 * @lastModify 2016/10/14
 * @param activity 页面实例
 * @return
 */
public void addActivity(Activity activity){
	if (activity == null)
		return;
	if(activityStack == null){
		activityStack = new Stack<Activity>();
	}
	activityStack.add(activity);
}
 
Example #28
Source File: CurrentUserActivity.java    From GcmForMojo with GNU General Public License v3.0 5 votes vote down vote up
private static void verifyStoragePermissions(Activity activity) {
    // Check if we have read or write permission
    int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

    if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}
 
Example #29
Source File: SigninManager.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private void progressSignInFlowSeedSystemAccounts() {
    if (AccountTrackerService.get(mContext).checkAndSeedSystemAccounts()) {
        progressSignInFlowCheckPolicy();
    } else if (AccountIdProvider.getInstance().canBeUsed(mContext)) {
        mSignInState.blockedOnAccountSeeding = true;
    } else {
        Activity activity = mSignInState.activity;
        UserRecoverableErrorHandler errorHandler = activity != null
                ? new UserRecoverableErrorHandler.ModalDialog(activity)
                : new UserRecoverableErrorHandler.SystemNotification();
        ExternalAuthUtils.getInstance().canUseGooglePlayServices(mContext, errorHandler);
        Log.w(TAG, "Cancelling the sign-in process as Google Play services is unavailable");
        abortSignIn();
    }
}
 
Example #30
Source File: SpinnerAdapter.java    From uservoice-android-sdk with MIT License 5 votes vote down vote up
public SpinnerAdapter(Activity context, List<T> objects) {
    this.objects = objects;
    inflater = context.getLayoutInflater();
    TypedValue tv = new TypedValue();
    context.getTheme().resolveAttribute(android.R.attr.textColorPrimary, tv, true);
    color = context.getResources().getColor(tv.resourceId);
}