我有两个活动,MainActivityCaller和MainActivity,活动MainActivityCaller通过startActivity()方法启动活动MainActivity。从Android中的通知有条件地重新启动活动
从通知中,我想要启动活动MainActivity(如果它已暂停但存在于任务返回堆栈中)(使用下面的代码完成),但要启动MainActivityCaller(如果没有)(例如,如果MainActivity实例具有已被用户或系统销毁)。
MainActivity广播以下当用户的位置改变
@Override
public void onLocationChanged(Location location) {
final Location finalLocation = location;
final Intent restartMainActivity = new Intent(this, MainActivity.class);
sendOrderedBroadcast(
new Intent(LOCATION_CHANGED_ACTION),
null,
new BroadcastReceiver() {
@TargetApi(16)
@Override
public void onReceive(Context context, Intent intent) {
if (getResultCode() != RESULT_OK) {
PendingIntent pi = PendingIntent.getActivity(context, 0, restartMainActivity, 0);
Notification.Builder nb = new Notification.Builder(context)
.setAutoCancel(true)
.setContentText("Lat = " + Double.toString(finalLocation.getLatitude()) + "\nLong = " + Double.toString(finalLocation.getLongitude()))
.setContentIntent(pi)
.setSmallIcon(android.R.drawable.stat_sys_warning));
NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, nb.build());
}
}
},
null,
0,
null,
null);
}
MainActivity还具有在其onCreate方法(以下缩写版本)实例化的广播接收机
@Override
protected void onCreate(Bundle savedInstanceState) {
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (isOrderedBroadcast())
setResultCode(RESULT_OK);
}
};
}
随着接收机中被注册onResume方法
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(LOCATION_CHANGED_ACTION);
registerReceiver(mReceiver, intentFilter);
}
与未注册的的onPause方法
@Override
protected void onPause() {
super.onPause();
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
}
在manifest文件中,MainActivity声明仅是被启动的一个任务
<activity android:name=".MainActivity"
android:launchMode="singleTask" />
眼下这无论是创建或重新启动MainActivity(取决于如果MainActivity被摧毁或停止)。当任何任务返回栈中不存在MainActivity的实例时,如何修改它以启动MainActivityCaller?
谢谢!