第一種顯示通知的方法:
- /**
- * notification
- *
- * @param id
- */
- private void showNotification()
- {
- RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
- views.setImageViewResource(R.id.icon, R.drawable.fm_icon);
- views.setTextViewText(R.id.fm_run, getString(R.string.fm_run));
- Notification status = new Notification();
- status.contentView = views;
- status.flags |= Notification.FLAG_ONGOING_EVENT;
- status.icon = R.drawable.ic_fm_status_bar;
- status.contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, FMEntryView.class).addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT), 0);
- startForeground(PLAYBACKSERVICE_STATUS, status);
- }
刪除通知:
- /**
- * delete notification
- */
- private void deleteNotification()
- {
- NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- nm.cancel(PLAYBACKSERVICE_STATUS);
- stopForeground(true);
- }
第二種顯示通知的方法:
- public void showNotification(int icon,String tickertext,String title,String content){
- //設置一個唯一的ID,隨便設置
-
- //Notification管理器
- Notification notification=new Notification(icon,tickertext,System.currentTimeMillis());
- //後面的參數分別是顯示在頂部通知欄的小圖標,小圖標旁的文字(短暫顯示,自動消失)系統當前時間(不明白這個有什麼用)
- notification.defaults=Notification.DEFAULT_ALL;
- //這是設置通知是否同時播放聲音或振動,聲音為Notification.DEFAULT_SOUND
- //振動為Notification.DEFAULT_VIBRATE;
- //Light為Notification.DEFAULT_LIGHTS,在我的Milestone上好像沒什麼反應
- //全部為Notification.DEFAULT_ALL
- //如果是振動或者全部,必須在AndroidManifest.xml加入振動權限
- PendingIntent pt=PendingIntent.getActivity(this, 0, new Intent(this,main.class), 0);
- //點擊通知後的動作,這裡是轉回main 這個Acticity
- notification.setLatestEventInfo(this,title,content,pt);
- nm.notify(notification_id, notification);
- }
- //showNotification(R.drawable.home,"圖標邊的文字","標題","內容");
刪除通知:
- nm.cancel(notification_id);
上面此法別忘了增加權限:
- <-permission android:name="android.permission.VIBRATE" /> <!-- 允許振動 -->
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11