Java源码示例:android.app.Activity
示例1
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);
}
示例2
/**
* 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;
}
示例3
/**
* 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);
}
}
示例4
/**
* 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;
}
示例5
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();
}
}
示例6
@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);
}
示例7
/**
* 声音设备权限
* @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;
}
示例8
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);
}
}
}
}
示例9
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;
}
示例10
/**
* 获取设备唯一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);
}
});
}
示例11
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();
}
示例12
/**
* 调整窗口的透明度 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();
}
示例13
/**
* 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;
}
示例14
@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();
}
}
});
}
}
示例15
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
);
}
}
示例16
@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);
}
}
示例17
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);
}
}
示例18
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;
}
示例19
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(); }
}
示例20
@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();
}
}
示例21
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;
}
示例22
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);
}
示例23
/**
* 隐藏加载的片名
*/
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);
}
});
}
示例24
@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);
}
}
示例25
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);
}
}
}
}
示例26
@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;
}
示例27
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof ActionOnPayListener) {
actionOnPayListener = (ActionOnPayListener) activity;
}
}
示例28
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();
}
}
示例29
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);
}
示例30
/**
* 添加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);
}