【达内课程】Android中的Notification

什么是通知

通知是Android中Service与用户交互的一种方式(主要是Service)

《【达内课程】Android中的Notification》

一个发送通知的栗子:

private static final int NOTIFICATION_ID = 1001;
private void sendNotification() {
        //1、NotificationManager
        NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        /** 2、Builder->Notification
         *  必要属性有三项
         *  小图标,通过 setSmallIcon() 方法设置
         *  标题,通过 setContentTitle() 方法设置
         *  内容,通过 setContentText() 方法设置*/
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentInfo("Content info")
                .setContentText("Content text")//设置通知内容
                .setContentTitle("Content title")//设置通知标题
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setSmallIcon(R.mipmap.ic_launcher_round)//不能缺少的一个属性
                .setSubText("Subtext")
                .setTicker("滚动消息......")
                .setWhen(System.currentTimeMillis());//设置通知时间,默认为系统发出通知的时间,通常不用设置
        Notification n = builder.build();
        //3、manager.notify()
        manager.notify(NOTIFICATION_ID,n);
}

运行在API22的手机上效果:
《【达内课程】Android中的Notification》

Android 8.0不能弹出通知

运行在API26的手机上怎么样呢…原来根本就不能弹出通知,填坑请戳下文:
Notification Android8.0中无法发送通知,提示:No Channel found for pkg

一个兼容8.0的栗子

《【达内课程】Android中的Notification》

private static final int NOTIFICATION_ID = 1001;
private void sendNotification() {
        //1、NotificationManager
        NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        /** 2、Builder->Notification
         *  必要属性有三项
         *  小图标,通过 setSmallIcon() 方法设置
         *  标题,通过 setContentTitle() 方法设置
         *  内容,通过 setContentText() 方法设置*/
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentInfo("Content info")
                .setContentText("Content text")//设置通知内容
                .setContentTitle("Content title")//设置通知标题
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setSmallIcon(R.mipmap.ic_launcher_round)//不能缺少的一个属性
                .setSubText("Subtext")
                .setTicker("滚动消息......")
                .setWhen(System.currentTimeMillis());//设置通知时间,默认为系统发出通知的时间,通常不用设置

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("001","my_channel",NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true); //是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.GREEN); //小红点颜色
            channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
            manager.createNotificationChannel(channel);
            builder.setChannelId("001");
        }

        Notification n = builder.build();
        //3、manager.notify()
        manager.notify(NOTIFICATION_ID,n);
}

让通知常驻通知栏

《【达内课程】Android中的Notification》

//让通知常驻通知栏
builder.setOngoing(true);

或者

Notification n = builder.build();
n.flags = Notification.FLAG_NO_CLEAR;

如何清除通知

 private void clearNotification() {
        //单利的系统服务
        NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(NOTIFICATION_ID);
    }

如何更新通知界面内容

《【达内课程】Android中的Notification》

    private static final int NOTIFICATION_ID2 = 1002;
	private int progress = 0;
    private void sendNotification2() {
        NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("音乐下载")
                .setContentText("下载进度:"+progress+"%")
                .setSmallIcon(R.mipmap.ic_launcher)                ;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("002","download_channel",NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
            builder.setChannelId("002");
        }
        Notification n = builder.build();
        manager.notify(NOTIFICATION_ID2,n);
        progress+=10;
    }

点击通知执行意图

《【达内课程】Android中的Notification》

sendNotification2方法修改如下:

Intent intent = new Intent(this,Main2Activity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
//给通知添加点击意图
builder.setContentIntent(pi);

《【达内课程】Android中的Notification》

如何实现进度条的通知

《【达内课程】Android中的Notification》

private void sendProgressNotification() {
        final NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        final Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("进度")
                .setContentText("进度...")
                .setProgress(100,10,true);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("003","download_channel",NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
            builder.setChannelId("003");
        }

        Notification n = builder.build();
        manager.notify(NOTIFICATION_ID3,n);
        //每隔1秒更新进度条进度
        //启动工作线程
        new Thread(){
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for(int i=1;i<=10;i++){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //发通知
                    builder.setProgress(100,i*10,false);
                    Notification n = builder.build();
                    manager.notify(NOTIFICATION_ID3,n);
                }
                //更新通知内容
                manager.cancel(NOTIFICATION_ID3);
                builder.setProgress(0,0,false);
                builder.setContentText("音乐下载完毕");
                Notification n = builder.build();
                manager.notify(NOTIFICATION_ID3,n);
            }
        }.start();
    }

《【达内课程】Android中的Notification》

如何自定义通知的UI界面

《【达内课程】Android中的Notification》

《【达内课程】Android中的Notification》
《【达内课程】Android中的Notification》

public class NotificationActivity extends Activity implements View.OnClickListener{
    private static final int NOTIFICATION_ID3 = 1003;
    private static final int NOTIFICATION_ID4 = 1004;
    Button button;
    Button button2;
    private MyReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_notification);

        button = findViewById(R.id.button);
        button.setOnClickListener(this);
        button2 = findViewById(R.id.button2);
        button2.setOnClickListener(this);

        //动态注册广播接收器
        receiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ACTION_BUTTON_PAUSE_CLICKED");
        this.registerReceiver(receiver,intentFilter);
    }

    class MyReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("info","接收到了广播"+intent.getAction());
        }
    }

    @Override
    protected void onDestroy() {
        this.unregisterReceiver(receiver);
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button:
                sendProgressNotification();
                break;
            case R.id.button2:
                sendCustomeNotification();
                break;
        }
    }

    public void sendCustomeNotification() {
        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        RemoteViews views = new RemoteViews(getPackageName(),R.layout.layout_notification);
        //给views中的按钮添加点击意图
        Intent intent = new Intent(this,NewsContentActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.btn_pre,pendingIntent);
        //给中间按钮添加点击意图
        Intent intent1 = new Intent("ACTION_BUTTON_PAUSE_CLICKED");
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this,0,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.btn_pause,pendingIntent1);

        builder.setContent(views);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("004","download_channel",NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
            builder.setChannelId("004");
        }
        Notification n = builder.build();
        manager.notify(NOTIFICATION_ID4,n);
    }

    private void sendProgressNotification() {
        final NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        final Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("进度")
                .setContentText("进度...")
                .setProgress(100,10,true);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("003","download_channel",NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
            builder.setChannelId("003");
        }

        Notification n = builder.build();
        manager.notify(NOTIFICATION_ID3,n);
        //每隔1秒更新进度条进度
        //启动工作线程
        new Thread(){
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for(int i=1;i<=10;i++){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //发通知
                    builder.setProgress(100,i*10,false);
                    Notification n = builder.build();
                    manager.notify(NOTIFICATION_ID3,n);
                }
                //更新通知内容
                manager.cancel(NOTIFICATION_ID3);
                builder.setProgress(0,0,false);
                builder.setContentText("音乐下载完毕");
                Notification n = builder.build();
                manager.notify(NOTIFICATION_ID3,n);
            }
        }.start();
    }
}
    原文作者:Errol_King
    原文地址: https://blog.csdn.net/u010356768/article/details/83382446
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞