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 Project: Klyph   Author: jonathangerbaud   File: AppLinkData.java    License: 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 Project: DialogUtil   Author: hss01248   File: DialogsMaintainer.java    License: 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 Project: google-media-framework-android   Author: googleads   File: LayerManager.java    License: 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 #4
Source Project: TakePhoto   Author: crazycodeboy   File: TImageFiles.java    License: 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 #5
Source Project: apollo-DuerOS   Author: ApolloAuto   File: PreferenceUtil.java    License: 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 #6
Source Project: commcare-android   Author: dimagi   File: EntityDetailView.java    License: 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 Project: MissZzzReader   Author: MissZzz1   File: PermissionHelper.java    License: 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 #8
Source Project: DroidPlugin   Author: DroidPluginTeam   File: RunningActivities.java    License: 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 Project: Coloring-book   Author: AlexZaiats   File: SlideAdapter.java    License: 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 #10
Source Project: AndroidBase   Author: lujianzhao   File: TelephoneUtil.java    License: 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 #11
Source Project: bitmask_android   Author: leapcode   File: EipFragment.java    License: 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 #12
Source Project: BookReader   Author: smuyyh   File: ScreenUtils.java    License: 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 Project: Android   Author: connectim   File: PermissiomUtilNew.java    License: 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 Project: Orin   Author: aliumujib   File: UpdateToastMediaScannerCompletionListener.java    License: 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 Project: GcmForMojo   Author: heipidage   File: CurrentUserActivity.java    License: 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 #16
Source Project: MNProgressHUD   Author: maning0303   File: StatusBarUtil.java    License: Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
public static void setDarkMode(Activity activity) {
    setMIUIStatusBarDarkIcon(activity, false);
    setMeizuStatusBarDarkIcon(activity, false);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }
}
 
Example #17
Source Project: GiraffePlayer2   Author: tcking   File: GiraffePlayer.java    License: Apache License 2.0 5 votes vote down vote up
private void removeFloatContainer() {
    Activity activity = getActivity();
    if (activity != null) {
        View floatBox = activity.findViewById(R.id.player_display_float_box);
        if (floatBox != null) {
            VideoInfo.floatView_x = floatBox.getX();
            VideoInfo.floatView_y = floatBox.getY();
        }
        removeFromParent(floatBox);
    }
}
 
Example #18
Source Project: imsdk-android   Author: qunarcorp   File: SystemBarTintManager.java    License: MIT License 5 votes vote down vote up
private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) {
    Resources res = activity.getResources();
    mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
    mSmallestWidthDp = getSmallestWidthDp(activity);
    mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
    mActionBarHeight = getActionBarHeight(activity);
    mNavigationBarHeight = getNavigationBarHeight(activity);
    mNavigationBarWidth = getNavigationBarWidth(activity);
    mHasNavigationBar = (mNavigationBarHeight > 0);
    mTranslucentStatusBar = translucentStatusBar;
    mTranslucentNavBar = traslucentNavBar;
}
 
Example #19
Source Project: UltimateAndroid   Author: cymcsg   File: ActivityTransitiorSecond.java    License: Apache License 2.0 5 votes vote down vote up
public void back(View v)
{
	this.finish();
	try
	{
		ActivityAnimator anim = new ActivityAnimator();
		anim.getClass().getMethod(this.getIntent().getExtras().getString("backAnimation") + "Animation", Activity.class).invoke(anim, this);
	}
	catch (Exception e) { Toast.makeText(this, "An error occured " + e.toString(), Toast.LENGTH_LONG).show(); }
}
 
Example #20
Source Project: frenchtoast   Author: pyricau   File: FrenchToast.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void onActivityDestroyed(Activity activity) {
  Holder holder = createdActivities.remove(activity);
  if (holder.queueOrNull == null) {
    return;
  }
  if (activity.isChangingConfigurations() && holder.savedUniqueId != null) {
    retainedQueues.put(holder.savedUniqueId, holder.queueOrNull);
    // onCreate() is always called from the same message as the previous onDestroy().
    MAIN_HANDLER.post(clearRetainedQueues);
  } else {
    holder.queueOrNull.clear();
  }
}
 
Example #21
Source Project: imsdk-android   Author: qunarcorp   File: QtalkServiceRNViewInstanceManager.java    License: MIT License 5 votes vote down vote up
public static String getLocalBundleFilePath(Activity mActivity) {
    QtalkServiceRNViewInstanceManager.JS_BUNDLE_LOCAL_BASE_PATH =
            mActivity.getApplicationContext().getFilesDir().getPath() +
                    File.separator + "rnRes" + File.separator + "qtalk_rn_service" + File.separator;

    return JS_BUNDLE_LOCAL_BASE_PATH + CACHE_BUNDLE_NAME;
}
 
Example #22
Source Project: Place-Search-Service   Author: Attriumph   File: PlaceSearchFragment.java    License: MIT License 5 votes vote down vote up
private void requestPermissions() {
    boolean shouldProvideRationale =
            ActivityCompat.shouldShowRequestPermissionRationale((Activity) context,
                    Manifest.permission.ACCESS_FINE_LOCATION);
    requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
            REQUEST_PERMISSIONS_REQUEST_CODE);
}
 
Example #23
Source Project: Dota2Helper   Author: uin3566   File: YoukuPluginPlayer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 隐藏加载的片名
 */
private void hideLoadinfo() {
    if (null != mActivity)
        ((Activity) mActivity).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != interactFrameLayout)
                    interactFrameLayout.removeView(loadingInfoLayout);

                if (null != loadInfoHandler)
                    loadInfoHandler.removeCallbacksAndMessages(null);
            }
        });

}
 
Example #24
Source Project: Dota2Helper   Author: uin3566   File: CachedVideoAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onClickItem(int position) {
    if (!mData.isEmpty() && position == getCachedCountPosition()) {
        return;
    }
    super.onClickItem(position);
    if (!mIsEditState) {
        DownloadInfo info = getItem(position);
        FullScreenVideoActivity.startFullScreenVideoActivity((Activity) mContext, info.videoid, info.imgUrl);
    }
}
 
Example #25
Source Project: smartcard-reader   Author: doc-rj   File: Console.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Console(Activity activity, Bundle inState, int testMode,
               ListView listView, ViewSwitcher switcher) {
    mActivity = activity;
    mTestMode = testMode;
    mListView = listView;

    // persistent data in shared prefs
    SharedPreferences ss = activity.getSharedPreferences("prefs", Context.MODE_PRIVATE);
    mEditor = ss.edit();
    mHandler = new Handler();

    mMsgAdapter = new MessageAdapter(activity.getLayoutInflater(), inState, this);
    listView.setAdapter(mMsgAdapter);

    mSwitcher = switcher;
    if (switcher != null) {
        if (activity.getResources().getConfiguration().orientation ==
                Configuration.ORIENTATION_LANDSCAPE) {
            // in landscape, switch to console messages and disable switching
            switcher.setDisplayedChild(VIEW_MESSAGES);
            mSwitcher = null;
        } else {
            if (mMsgAdapter.getCount() > 0) {
                switcher.setDisplayedChild(VIEW_MESSAGES);
            }
        }
    }
}
 
Example #26
Source Project: ShaderEditor   Author: markusfisch   File: Sampler2dPropertiesFragment.java    License: MIT License 5 votes vote down vote up
@Override
public View onCreateView(
		LayoutInflater inflater,
		ViewGroup container,
		Bundle state) {
	Activity activity = getActivity();
	activity.setTitle(R.string.texture_properties);

	Bundle args;
	View view;

	if ((args = getArguments()) == null ||
			(imageUri = args.getParcelable(
					IMAGE_URI)) == null ||
			(cropRect = args.getParcelable(
					CROP_RECT)) == null ||
			(view = initView(
					activity,
					inflater,
					container)) == null) {
		activity.finish();
		return null;
	}

	imageRotation = args.getFloat(ROTATION);

	return view;
}
 
Example #27
Source Project: CreditCardView   Author: Movile   File: CreditCardFragment.java    License: 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 #28
Source Project: AndroidChromium   Author: JackyAndroid   File: SigninManager.java    License: 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 #29
Source Project: uservoice-android-sdk   Author: uservoice   File: SpinnerAdapter.java    License: 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);
}
 
Example #30
Source Project: HttpRequest   Author: leibing8912   File: AppManager.java    License: 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);
}