歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android添加通知到頂部任務欄

Android添加通知到頂部任務欄

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

Android添加通知到頂部任務欄

  1. public class NotificationtestActivity extends Activity {
  2. private static final int ID = 1213;
  3. private static final String KEY_COUNT="keyCount";
  4. private int count;
  5. @Override
  6. public void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.main);
  9. Intent intent=this.getIntent();
  10. count=intent.getIntExtra(KEY_COUNT,0);
  11. this.setTitle("這是第"+Integer.toString(count)+"個");
  12. Button btn=(Button) this.findViewById(R.id.button1);
  13. btn.setOnClickListener(new View.OnClickListener() {
  14. @Override
  15. public void onClick(View v) {
  16. AddNotification();
  17. NotificationtestActivity.this.finish();
  18. }
  19. });
  20. }
  21. /**
  22. * 添加頂部通知
  23. * @author liuzhao
  24. */
  25. public void AddNotification(){
  26. count++;
  27. //添加通知到頂部任務欄
  28. //獲得NotificationManager實例
  29. String service = NOTIFICATION_SERVICE;
  30. NotificationManager nm = (NotificationManager)getSystemService(service);
  31. //實例化Notification
  32. Notification n = new Notification();
  33. //設置顯示圖標
  34. int icon = R.drawable.icon;
  35. //設置提示信息
  36. String tickerText ="我的程序";
  37. //顯示時間
  38. long when = System.currentTimeMillis();
  39. n.icon = icon;
  40. n.tickerText = tickerText;
  41. n.when = when;
  42. //顯示在“正在進行中”
  43. // n.flags = Notification.FLAG_ONGOING_EVENT;
  44. n.flags|=Notification.FLAG_AUTO_CANCEL; //自動終止
  45. //實例化Intent
  46. Intent it = new Intent(this,NotificationtestActivity.class);
  47. it.putExtra(KEY_COUNT, count);
  48. /*********************
  49. *獲得PendingIntent
  50. *FLAG_CANCEL_CURRENT:
  51. * 如果當前系統中已經存在一個相同的PendingIntent對象,
  52. * 那麼就將先將已有的PendingIntent取消,然後重新生成一個PendingIntent對象。
  53. *FLAG_NO_CREATE:
  54. * 如果當前系統中不存在相同的PendingIntent對象,
  55. * 系統將不會創建該PendingIntent對象而是直接返回null。
  56. *FLAG_ONE_SHOT:
  57. * 該PendingIntent只作用一次,
  58. * 如果該PendingIntent對象已經觸發過一次,
  59. * 那麼下次再獲取該PendingIntent並且再觸發時,
  60. * 系統將會返回一個SendIntentException,在使用這個標志的時候一定要注意哦。
  61. *FLAG_UPDATE_CURRENT:
  62. * 如果系統中已存在該PendingIntent對象,
  63. * 那麼系統將保留該PendingIntent對象,
  64. * 但是會使用新的Intent來更新之前PendingIntent中的Intent對象數據,
  65. * 例如更新Intent中的Extras。這個非常有用,
  66. * 例如之前提到的,我們需要在每次更新之後更新Intent中的Extras數據,
  67. * 達到在不同時機傳遞給MainActivity不同的參數,實現不同的效果。
  68. *********************/
  69. PendingIntent pi = PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT);
  70. //設置事件信息,顯示在拉開的裡面
  71. n.setLatestEventInfo(NotificationtestActivity.this,"我的軟件"+Integer.toString(count), "我的軟件正在運行……", pi);
  72. //發出通知
  73. nm.notify(ID,n);
  74. }
  75. }

Copyright © Linux教程網 All Rights Reserved