【发布时间】:2014-02-27 20:11:41
【问题描述】:
我有两个活动,MainActivityCaller 和 MainActivity,活动 MainActivityCaller 通过 startActivity() 方法启动活动 MainActivity。
从通知中,如果 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?
谢谢!
【问题讨论】:
标签: android android-intent android-activity broadcastreceiver android-notifications