[英]Android app automatically coming to foreground
In my application in FirstActivity Asynctask is called at the end of asyntask secondactivity will be opened 在我的FirstActivity应用程序中,异步任务结束时调用了Asynctask,secondactivity将被打开
when app is in background when asyntask is running after completion of async task Application automatically coming to foreground without any user interaction 当应用程序在后台运行时,异步任务完成后运行asyntask时,应用程序自动进入前台,而无需任何用户交互
how to avoid it? 如何避免呢?
In android we can find the app is in foreground or background like this: 在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
}
Check if your application is in foreground before starting the second activity using a method like this: 在开始第二个活动之前,请使用以下方法检查应用程序是否处于前台:
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;
}
Check Whether any Activity is opened or Not. 检查是否打开了任何活动。
/***
* 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;
}
Use this like: 像这样使用:
if(isForeground(context)) {
//Nothing to do
} else {
/**
You can do here what you want to do
**/
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.