【Android】Notification相关

1,概述

通知功能,不必多说。大致过程是系统app(如systemui)通过NotificationListenerService.registerAsSystemService将自己注册到系统通知观察者集合中,应用进程发送通知后,系统通知系统应用进程回调如下方法(具体可查看NotificationListener源码),

NotificationListener.onNotificationPosted;

NotificationListener.onNotificationUpdate;

NotificationListener.onNotificationRemove;

systemui便拿到Notification,根据自定义样式infalte视图展示;

因此,通知机制是跨进程的,在应用进程-系统进程-系统应用进程间传递,本文关注点在应用进程发送通知过程,对于系统进程以及系统应用进程不关心。

2,应用进程实例


public class NotificationTestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification_test);

        /**通知基本使用*/
        //拿到nms
        NotificationManager notificationManager = getSystemService(NotificationManager.class);

        //跳转相关,实现了Parcelable接口,需跨进程;第一个参数是MainActivity,传入intent是MainActivity跳转至目标Activity
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        //自定义ui,传入布局
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.activity_notification_test);
        remoteViews.setOnClickPendingIntent(R.id.actionDown, //给指定id设置点击事件
                PendingIntent.getBroadcast(this, 1, new Intent("com.zjw.demotest.自定义广播字段"),
                        PendingIntent.FLAG_CANCEL_CURRENT));
        //构造者模式,创建通知
        Notification.Builder notificationBuilder = new Notification.Builder(getApplicationContext(), "channelId");
        @SuppressLint("WrongConstant") Notification notification = notificationBuilder.setContentTitle("设置通知标题")
                .setContentText("设置通知内容")
                .setWhen(System.currentTimeMillis())//设置时间
                .setSmallIcon(R.mipmap.ic_launcher)//设置小图标
                .setLargeIcon(BitmapFactory.decodeFile(""))//设置大图标
                .setContentIntent(pendingIntent)//设置跳转intent
                .setAutoCancel(true)//设置点击后自动取消
                .setSound(Uri.fromFile(new File(""))) //设置提示音
                .setVibrate(new long[]{0, 1000, 1000, 1000}) // 设置震动,需要添加求权限 <uses-permission android:name="android.permission.VIBRATE"/>
                .setLights(Color.GREEN, 1000, 1000) // 设置闪烁
                .setDefaults(NotificationCompat.DEFAULT_ALL) // 使用手机默认效果
                .setPriority(NotificationCompat.PRIORITY_MAX)// 设置重要程度
                .setStyle(new Notification.BigTextStyle().bigText("长文"))//设置特殊样式,还有大图style
                .setCustomContentView(remoteViews)//设置通知远程view,
                .build();

        //通知系统进程,最后调用systemui下onNotificationPost方法
        notificationManager.notify(1, notification);

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值