Android:如何防止活动在后台启动并前往
问题描述:
在我的应用程序中,我有一个系统,我可以从应用程序中的任何位置显示对话框,甚至可以从辅助线程显示对话框。当我收到来自服务器的一些通知,我只是将对话框放在用户眼前(对话框显示在从应用程序上下文打开的透明活动中)。我的问题是,当应用程序在后台并从服务器接收信号时,它会启动包含对话框的透明活动,所以应用程序会在前台显示 - 这是违反android(和我的)规则的。Android:如何防止活动在后台启动并前往
我创建了一个通知系统,以便显示来自服务器的收件人是状态栏。 我与透明活动(持有对话框)的通知相关联,所以当用户点击通知时,会被带到对话框。
Intent notificationIntent = new Intent(CVSApplication.getInstance(), CVSDialogActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(CVSApplication.getInstance(), 0, notificationIntent, 0);
问题是应用程序无论如何都被带到前面,即使用户没有点击通知。
当startActivity被调用时,有没有什么办法可以防止从背景返回CVSDialogActivity? 这里是一个开始CVSDialogActivity意图:
intent = new Intent(app, CVSDialogActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(USE_CUSTOM_CONTENT, false);
intent.putExtra(INSTANCE, this.hashCode());
我也试过这个变体:
intent = new Intent(app, CVSDialogActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_FROM_BACKGROUND);
intent.putExtra(USE_CUSTOM_CONTENT, false);
intent.putExtra(INSTANCE, this.hashCode());
,但是当startActivity(意向)被称为应用程序被带到前面(我想显示包含对话框的活动,但在后台,以及当用户点击通知时,将应用程序放到前台)。
谢谢, 亚历克斯
答
我已经找到一种方法来解决这个问题。我创建了一个系统,它告诉我,如果应用程序是在背景或没有(使用正在运行的进程)就像这样:
public boolean isInBackground(){
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses= activityManager.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
PackageInfo p = null;
try {
p = this.getPackageManager().getPackageInfo(appProcess.pkgList[0], PackageManager.GET_PERMISSIONS);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if(p != null && p.packageName.equals(getPackageName()) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!Is in background: false");
return false;
}
}
System.out.println("!!!!!!!!!!!!!!!!!!!!!Is in background: true");
return true;
}
现在,如果我在后台,我就不展开对话,我将开始只是通知,并且当通知被按下时,应用程序被带到前面,并且对话框被显示给用户。
Alex。