歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android Notification顯示通知的兩種方法

Android Notification顯示通知的兩種方法

日期:2017/3/1 10:24:21   编辑:Linux編程

第一種顯示通知的方法:

  1. /**
  2. * notification
  3. *
  4. * @param id
  5. */
  6. private void showNotification()
  7. {
  8. RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
  9. views.setImageViewResource(R.id.icon, R.drawable.fm_icon);
  10. views.setTextViewText(R.id.fm_run, getString(R.string.fm_run));
  11. Notification status = new Notification();
  12. status.contentView = views;
  13. status.flags |= Notification.FLAG_ONGOING_EVENT;
  14. status.icon = R.drawable.ic_fm_status_bar;
  15. status.contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, FMEntryView.class).addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT), 0);
  16. startForeground(PLAYBACKSERVICE_STATUS, status);
  17. }

刪除通知:

  1. /**
  2. * delete notification
  3. */
  4. private void deleteNotification()
  5. {
  6. NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  7. nm.cancel(PLAYBACKSERVICE_STATUS);
  8. stopForeground(true);
  9. }

第二種顯示通知的方法:

  1. public void showNotification(int icon,String tickertext,String title,String content){
  2. //設置一個唯一的ID,隨便設置
  3. //Notification管理器
  4. Notification notification=new Notification(icon,tickertext,System.currentTimeMillis());
  5. //後面的參數分別是顯示在頂部通知欄的小圖標,小圖標旁的文字(短暫顯示,自動消失)系統當前時間(不明白這個有什麼用)
  6. notification.defaults=Notification.DEFAULT_ALL;
  7. //這是設置通知是否同時播放聲音或振動,聲音為Notification.DEFAULT_SOUND
  8. //振動為Notification.DEFAULT_VIBRATE;
  9. //Light為Notification.DEFAULT_LIGHTS,在我的Milestone上好像沒什麼反應
  10. //全部為Notification.DEFAULT_ALL
  11. //如果是振動或者全部,必須在AndroidManifest.xml加入振動權限
  12. PendingIntent pt=PendingIntent.getActivity(this, 0, new Intent(this,main.class), 0);
  13. //點擊通知後的動作,這裡是轉回main 這個Acticity
  14. notification.setLatestEventInfo(this,title,content,pt);
  15. nm.notify(notification_id, notification);
  16. }
  17. //showNotification(R.drawable.home,"圖標邊的文字","標題","內容");

刪除通知:

  1. nm.cancel(notification_id);

上面此法別忘了增加權限:

  1. <-permission android:name="android.permission.VIBRATE" /> <!-- 允許振動 -->

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved