我有一个活动 MyActivity 启动一个前台服务来播放音乐,一旦音乐完成,服务就会通过发送 sendOrderedBroadcast
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
.....
Intent intent = new Intent(MyActivity .this, MyMusicPlayerService.class);
startService(intent);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter from_sendorderedNotification = new IntentFilter(ACTION_SESSION_COMPLETE);
registerReceiver(notificationsessionComplted, from_sendorderedNotification);
}
BroadcastReceiver notificationsessionComplted = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("xa", "onRecive of activity Send Boarcast by order ****************");
}
};
}
MyMusicPlayerService.java
public class MyMusicPlayerServiceextends Service {
public static final String ACTION_SESSION_COMPLETE = "my.action.COMPLETE";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
......
....Start mediaplayer and set setOnCompletionListener....
return START_STICKY;
}
public void onCompletion(MediaPlayer _mediaPlayer){
stopForeground(true);
stopSelf();
Intent i = new Intent();
i.setAction(ACTION_SESSION_COMPLETE);
MyMusicPlayerServiceextends .this.sendOrderedBroadcast(i, null);
}
}
发送通知.java
public class SendNotification extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
Notification notification = ....
notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(arg0, MyActivity .class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
PendingIntent contentIntent = PendingIntent.getActivity(arg0, 0, intent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
final int _ID = 10;
mNotificationManager.notify(_ID, notification);
}
主要文件
<service android:name="com.example.sendbroadcast.MyMusicPlayerService" />
<activity
android:name="com.example.sendbroadcast.MyActivity"
android:launchMode="singleTop"
android:noHistory="true">
<intent-filter android:priority="1" >
<action android:name="my.action.COMPLETE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver android:name="com.example.sendbroadcast.SendNotification" >
<intent-filter android:priority="2" >
<action android:name="my.action.COMPLETE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
我已在 MyActivity 的 onPause 中取消注册接收器,当 Activity 处于 onStop 状态时,接收器 SendNotification 将接收广播并通过通知通知用户,单击它会返回 MyActivity。假设 MyActivity 已销毁并将其从堆栈没有广播发送或接收。我可以知道为什么接收器在这种情况下无法接收。