我更喜欢您创建“returnFromNotify”活动的最初想法,而不是您提出的解决方法,因为可以检测 ResumeActivity 是否位于堆栈底部(因此是堆栈中的唯一活动)。
以下是您的操作方法:
将您的 ResumeActivity 添加到清单并指定noHistory属性:
<activity android:name=".ResumeActivity" android:noHistory="true" />
指定 noHistory 将确保此 Activity 在完成后不会留在堆栈中。这样你就知道只有当前正在运行的 ResumeActivity 实例才会出现在堆栈中。
为了检查应用程序堆栈,您还必须请求 GET_TASKS 权限:
<uses-permission android:name="android.permission.GET_TASKS" />
现在您可以使用ActivityManager::getRunningTasks()来确定 ResumeActivity 是否是堆栈中的唯一活动:
public class ResumeActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isOnlyActivityInStack()) { //check the application stack
//This activity is the only activity in the application stack, so we need to launch the main activity
Intent main = new Intent(this, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
} else {
//Return the user to the last activity they had open
this.finish();
}
}
/**
* Checks the currently running tasks. If this activity is the base activity, we know it's the only activity in the stack
*
* @return boolean This activity is the only activity in the stack?
**/
private boolean isOnlyActivityInStack() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
boolean onlyActivityInStack = false;
for(RunningTaskInfo tasks : manager.getRunningTasks(Integer.MAX_VALUE)) {
if(tasks.baseActivity.getPackageName().equals(this.getPackageName())) { //find this package's application stack
if(tasks.baseActivity.getClassName().equals(this.getClass().getName())) {
//If the ResumeActivity is the base activity, we know that it is the only activity in the stack
onlyActivityInStack = true;
break;
}
}
}
return onlyActivityInStack;
}
}
我知道你在 2 年前问过这个问题,但我会提供这个答案,以防其他人遇到这种特殊情况(就像我一样)。我认为您最初正在努力的解决方案是正确的。