任何地方
Intent intent = new Intent(ACTION); sendBroadcast(intent);
public class ActivityMain extends Activity {
public static final int ITEM0 = Menu.FIRST;
public static final int ITEM1 = Menu.FIRST + 1;
static final String ACTION_1 = " NEW_BROADCAST_1";
static final String ACTION_2 = " NEW_BROADCAST_2";
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, ITEM0, 0, "显示Notification");
menu.add(0, ITEM1, 0, "清除Notification");
menu.findItem(ITEM1);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ITEM0:
actionClickMenuItem1();
break;
case ITEM1:
actionClickMenuItem2();
break;
}
return true;
}
private void actionClickMenuItem1() {
Intent intent = new Intent(ACTION_1);
sendBroadcast(intent);
}
private void actionClickMenuItem2() {
Intent intent = new Intent(ACTION_2);
sendBroadcast(intent);
}
}
public class Receiver1 extends BroadcastReceiver {
Context context;
public static int NOTIFICATION_ID = 21321;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
showNotification();
}
private void showNotification() {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(
android.content.Context.NOTIFICATION_SERVICE);
Notification notification =
new Notification(R.drawable.icon,
"在Receiver1中",
System.currentTimeMillis());
PendingIntent contentIntent =
PendingIntent.getActivity(context, 0,
new Intent(context, ActivityMain.class), 0);
notification.setLatestEventInfo(
context, "在Receiver1中", null,
contentIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
public class Receiver2 extends BroadcastReceiver {
Context context;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
this.context = context;
DeleteNotification();
}
private void DeleteNotification() {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(
android.content.Context.NOTIFICATION_SERVICE);
notificationManager.cancel(
Receiver1.NOTIFICATION_ID);
}
}
<receiver android:name="dReceiver1"> <intent-filter> <action android:name=" NEW_BROADCAST_1"/> </intent-filter> </receiver> <receiver android:name="Receiver2"> <intent-filter> <action android:name=" NEW_BROADCAST_2"/> </intent-filter> </receiver>