我有兩個活動,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?
謝謝!