在我的应用程序中,FirstActivity Asynctask在asyntask结束时调用secondactivity将被打开
当asyntask正在运行时app处于后台 完成异步任务后应用程序自动进入前台而无需任何用户交互
如何避免它?
答案 0 :(得分:1)
在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
}
答案 1 :(得分:0)
在使用如下方法开始第二个活动之前,检查您的应用程序是否在前台:
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;
}
答案 2 :(得分:0)
检查是否打开了任何活动。
/***
* 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
**/
}