[英]Android app automatically coming to foreground
在我的FirstActivity應用程序中,異步任務結束時調用了Asynctask,secondactivity將被打開
當應用程序在后台運行時,異步任務完成后運行asyntask時,應用程序自動進入前台,而無需任何用戶交互
如何避免呢?
在android中,我們可以找到該應用位於前景或背景,如下所示:
ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Activity.ACTIVITY_SERVICE);
String className = activityManager.getRunningTasks(1).get(0).topActivity
.getClassName();
if (className.equals("your activity class name with package")) {
//ToDO
}
在開始第二個活動之前,請使用以下方法檢查應用程序是否處於前台:
public static boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
檢查是否打開了任何活動。
/***
* Checking Whether any Activity of Application is running or not
* @param context
* @return
*/
public boolean isForeground(Context context) {
// Get the Activity Manager
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// Get a list of running tasks, we are only interested in the last one,
// the top most so we give a 1 as parameter so we only get the topmost.
List< ActivityManager.RunningTaskInfo > task = manager.getRunningTasks(1);
// Get the info we need for comparison.
ComponentName componentInfo = task.get(0).topActivity;
// Check if it matches our package name.
if(componentInfo.getPackageName().equals(context.getPackageName()))
return true;
// If not then our app is not on the foreground.
return false;
}
像這樣使用:
if(isForeground(context)) {
//Nothing to do
} else {
/**
You can do here what you want to do
**/
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.