[关闭]
@ZSCDumin 2019-07-10T11:43:42.000000Z 字数 2031 阅读 1476

Android 发送通知的写法(兼容8.0以上版本)

Android


1、工具类(NotificationUtils)

  1. package com.zscdumin.zhixinapp.activity;
  2. import android.app.Notification;
  3. import android.app.NotificationChannel;
  4. import android.app.NotificationManager;
  5. import android.content.Context;
  6. import android.content.ContextWrapper;
  7. import android.os.Build;
  8. import android.support.annotation.RequiresApi;
  9. import android.support.v4.app.NotificationCompat;
  10. /**
  11. * Created by LaoZhao on 2017/11/19.
  12. */
  13. public class NotificationUtils extends ContextWrapper {
  14. private NotificationManager manager;
  15. public static final String id = "channel_1";
  16. public static final String name = "channel_name_1";
  17. public NotificationUtils(Context context){
  18. super(context);
  19. }
  20. @RequiresApi(api = Build.VERSION_CODES.O)
  21. public void createNotificationChannel(){
  22. NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
  23. getManager().createNotificationChannel(channel);
  24. }
  25. private NotificationManager getManager(){
  26. if (manager == null){
  27. manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  28. }
  29. return manager;
  30. }
  31. @RequiresApi(api = Build.VERSION_CODES.O)
  32. public Notification.Builder getChannelNotification(String title, String content){
  33. return new Notification.Builder(getApplicationContext(), id)
  34. .setContentTitle(title)
  35. .setContentText(content)
  36. .setSmallIcon(android.R.drawable.stat_notify_more)
  37. .setAutoCancel(true);
  38. }
  39. public NotificationCompat.Builder getNotification_25(String title, String content){
  40. return new NotificationCompat.Builder(getApplicationContext())
  41. .setContentTitle(title)
  42. .setContentText(content)
  43. .setSmallIcon(android.R.drawable.stat_notify_more)
  44. .setAutoCancel(true);
  45. }
  46. public void sendNotification(String title, String content){
  47. if (Build.VERSION.SDK_INT>=26){
  48. createNotificationChannel();
  49. Notification notification = getChannelNotification
  50. (title, content).build();
  51. getManager().notify(1,notification);
  52. }else{
  53. Notification notification = getNotification_25(title, content).build();
  54. getManager().notify(1,notification);
  55. }
  56. }
  57. }

2、使用

  1. private void sendNotification() {
  2. NotificationUtils notificationUtils = new NotificationUtils(this);
  3. notificationUtils.sendNotification("测试标题", "测试内容");
  4. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注