原理:
請(qǐng)求系統(tǒng)發(fā)送一個(gè)廣播,在本程序接收該廣播,并做一系列的操作,屬于跨進(jìn)程的開(kāi)發(fā)
1、點(diǎn)擊控件請(qǐng)求系統(tǒng)發(fā)送廣播
public void doClick(View v) {switch (v.getId()) {case R.id.btn_notification:sendNotification();// 發(fā)送通知break;
}
2、在通知欄需要顯示的通知樣式
/*** 自定義*/PRivate void sendNotificationZidinyi() {NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);Builder builder = new Builder(MainActivity.this);RemoteViews views = new RemoteViews(getPackageName(), R.layout.notification_zidinyi);//給RemoteViews添加點(diǎn)擊意圖Intent activityIntent = new Intent(MainActivity.this,MainActivity.class);PendingIntent pi5 = PendingIntent.getActivity(MainActivity.this, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);views.setOnClickPendingIntent(R.id.btn_startActivity, pi5);//給播放按鈕添加點(diǎn)擊意圖Intent broadIntent = new Intent("ACTION_SEND_BROADCAST");PendingIntent broadCastPi = PendingIntent.getBroadcast(MainActivity.this, 0, broadIntent , Context.BIND_DEBUG_UNBIND);views.setOnClickPendingIntent(R.id.img_player, broadCastPi);builder.setContentTitle("").setTicker("自定義").setSmallIcon(R.drawable.small_pic).setContent(views );Notification notifi = builder.build();manager.notify(555,notifi);}
3、動(dòng)態(tài)注冊(cè)廣播接收者
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);receiver = new PlayerBroadcastReceiver();IntentFilter filter = new IntentFilter();filter.addAction("ACTION_SEND_BROADCAST");registerReceiver(receiver, filter);}
4、寫一個(gè)清除通知的方法,在其生命周期結(jié)束時(shí)自行清除
private void clearNotification() {// 單例系統(tǒng)服務(wù),可重復(fù)創(chuàng)建NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);manager.cancel(NOTIFI_MANAGER_ID);}
@Overrideprotected void onDestroy() {// TODO Auto-generated method stubisDoing=false;NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);manager.cancel(588);unregisterReceiver(receiver);super.onDestroy();}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注