Android notification

Notification

通知是Android [Material Design] 的ui 比较重要的一环;

创建

为了适配大部分的版本 我们用v4 包下的 NotificationCompat.Builder 来创建获取Notification ;获取NotificationManager ,通过notify 来通知;
Notification 常见的设置;

  • setSmallIcon 设置小图标
  • setContentTitle 设置标题
  • ContentText 设置文本内容
  • setPriority() 设置优先级

PendingIntent 用来创建,点击通知的活动;
我们借用TaskStackBuilder 返回栈 来更好 来操作创建;
示例代码如下:

        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!");
// 创建点击返回的activity 
Intent resultIntent = new Intent(this, ResultActivity.class);

//创建返回栈
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
        );
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());

取消通知

  • 用户单独或通过使用“全部清除”清除了该通知(如果通知可以清除)。
  • 用户点击通知,且您在创建通知时调用了 setAutoCancel()
  • 您针对特定的通知 ID 调用了 cancel()。此方法还会删除当前通知。
  • 您调用了 cancelAll()]方法,该方法将删除之前发出的所有通知。

QA

国内部分手机的通知栏;需要在设置的内给予权限;(这也是国内开发者个工作比国外多的原因)

PendingIntent 一定要配置点击通知的需要返回的活动界面;如果不设置会导致 PendingIntent的空指针

本文参看 官网

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容