资讯专栏INFORMATION COLUMN

Notification 使用详解

sorra / 3184人阅读

摘要:简介通知在用户界面的一个重要部分,其使用方法请看以下内容继承关系如下简介通知是应用向用户显示的消息提示,当发送通知时,通知将先以图标的形式显示在通知区域中。通知区域和下拉通知栏均是由系统控制的区域,用户可以随时查看。

极力推荐文章:欢迎收藏
Android 干货分享

阅读五分钟,每日十点,和您一起终身学习,这里是程序员Android

本篇文章主要介绍 Android 开发中的部分知识点,通过阅读本篇文章,您将收获以下内容:

Notification 简介

通知的创建

通知的管理

简单的通知

可以 扩展的通知

通知中含下载进度条

通知中含媒体播放控件

自定义通知内容

Notification 通知是应用向用户显示的消息提示,当发送通知时,通知将先以图标的形式显示在通知区域中。用户可以打开下拉通知栏查看通知的详细信息。 通知区域和下拉通知栏均是由系统控制的区域,用户可以随时查看。

Notification 简介

通知在Android用户界面的一个重要部分,其使用方法请看以下内容:

Notification 继承关系如下:
java.lang.Object
   ↳
    android.app.Notification
1.Notification 简介

通知是应用向用户显示的消息提示,当发送通知时,通知将先以图标的形式显示在通知区域中。用户可以打开下拉通知栏查看通知的详细信息。 通知区域和下拉通知栏均是由系统控制的区域,用户可以随时查看。

2.创建Notification 的方法

调用NotificationCompat.Builder.build() 创建Notification 对象

然后调用 NotificationManager.notify() Notification 对象传递给系统。

Notification 对象必须包含以下内容:

小图标,由 setSmallIcon() 设置

标题,由 setContentTitle() 设置

详细文本,由 setContentText() 设置

通知可选内容

设置优先级

通知默认优先级为 PRIORITY_DEFAULT 0
Notification.Builder.setPriority()
5个级别可选(-2、-1、0、1、2)

通知优先级如下:

    PRIORITY_LOW=-1
    PRIORITY_MIN=-2
    PRIORITY_DEFAULT = 0
    PRIORITY_HIGH=1
    PRIORITY_MAX=2
设置可以扩展样式

通过Notification.Builder.setStyle()可以设置通知的样式。

点击通知启动Activity(PendingIntent)

通知中经常遇到,点击通知栏,打开 Activity


        Notification.Builder mBuilder = new Notification.Builder(this);

        mBuilder.setSmallIcon(R.drawable.gril)
                .setDefaults(Notification.DEFAULT_SOUND).setColor(000)
                .setContentTitle("简单通知Tittle").setContentText("点击可以打开Activity");

        Intent resultIntent = new Intent(this, NotificationMethods.class);
        // 新开一个Activity 栈

        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotificationMethods.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    
3. 通知的管理

更新通知

调用 NotificationManager.notify(ID) 发出带有通知 ID 的通知,ID相同,即可更新以前ID发送的通知。

删除通知

创建时 调用了 setAutoCancel(true)

删除时候调用删除指定ID

NotificationManager.cancel(notificationId)

删除自己应用发的所有通知

Utils.mNotificationManager.cancelAll();

在通知中显示进度条

setProgress()

4. 简单的通知

实现效果

实现代码

    /**
     * 简单通知
     */
    public void SimpleNotification(View view) {

        Notification.Builder mBuilder = new Notification.Builder(this);

        mBuilder.setSmallIcon(R.drawable.gril)
                .setDefaults(Notification.DEFAULT_SOUND).setColor(000)
                .setContentTitle("简单通知Tittle").setContentText("点击可以打开Activity");

        Intent resultIntent = new Intent(this, NotificationMethods.class);
        // 新开一个Activity 栈

        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotificationMethods.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    }
5. 可以 扩展的通知

实现效果

实现代码

    /**
     * 可扩展通知
     * **/
    public void NotificationStyle(View view) {

        Notification.Builder mBuilder = new Notification.Builder(this);

        mBuilder.setLargeIcon(
                DrawableUtils.DrawableToBitmap(getResources().getDrawable(
                        R.drawable.ic_launcher)))
                .setContentTitle("我是可扩展通知的Tittle ")
                .setDefaults(Notification.DEFAULT_SOUND)

                .setContentText("我是可扩展通知的内容")
                .setSmallIcon(R.drawable.ic_launcher)
                .setAutoCancel(true)
                .setStyle(
                        new Notification.InboxStyle().addLine("我是可扩展通知第一行")
                                .addLine("我是可扩展通知第二行")
                                .setBigContentTitle("我是可扩展的大 Tittle")
                                .setSummaryText("点击,展开获取更多内容"));

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 如果Id 一样可以更新通知
        mNotificationManager.notify(1, mBuilder.build());
    }
6. 通知中含下载进度条

实现效果

实现代码

    /**
     * 带有下载进度条的通知
     * **/
    public void NotificationProcess(View view) {

        final NotificationManager mNotifyManagerProcess;
        final Notification.Builder mBuilder;
        mNotifyManagerProcess = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new Notification.Builder(this);
        mBuilder.setContentTitle("Picture Downloading").setSmallIcon(
                R.drawable.ic_launcher);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (MIncr = 0; MIncr <= 100; MIncr += 1 + 5 * Math.random()) {
                    mBuilder.setProgress(100, MIncr, false).setContentText(
                            MIncr + "%");
                    mNotifyManagerProcess.notify(2, mBuilder.build());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    }
                }
                /**
                 * setProgress true 则表示 进度条一直不停的从左至右滑动,类似于圆形进度条 false :进度条消失
                 * **/
                mBuilder.setContentText("Download complete").setProgress(0, 0,
                        false);
                mNotifyManagerProcess.notify(2, mBuilder.build());
            }
        }).start();
    }
7. 通知中含媒体播放控件

实现效果

实现代码

    /**
     * 音乐播放器样式
     * **/
    public void NotificationMediaStyle(View view) {
        Notification.Builder mMediaBuilder = new Notification.Builder(this);
        mMediaBuilder.setSmallIcon(R.drawable.ic_launcher);
        mMediaBuilder.setContentTitle("如果有一天我变有钱");
        mMediaBuilder.setContentText("毛不易");
        mMediaBuilder.setLargeIcon(DrawableUtils
                .DrawableToBitmap(getResources().getDrawable(
                        R.drawable.ic_launcher)));
        Intent mIntent = new Intent();
        ComponentName name = new ComponentName(this, NotificationMethods.class);
        mIntent.setComponent(name);
        PendingIntent mPendingIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, mIntent, 0);
        mMediaBuilder.setContentIntent(mPendingIntent);
        mMediaBuilder.setPriority(Notification.PRIORITY_MAX);
        mMediaBuilder.addAction(new Notification.Action.Builder(Icon
                .createWithResource(NotificationMethods.this,
                        R.drawable.music_pre), "1", null).build());
        mMediaBuilder.addAction(new Notification.Action.Builder(Icon
                .createWithResource(NotificationMethods.this,
                        R.drawable.music_play), "2", null).build());
        mMediaBuilder.addAction(new Notification.Action.Builder(Icon
                .createWithResource(NotificationMethods.this,
                        R.drawable.music_next), "3", null).build());

        Notification.MediaStyle mMediaStyle = new Notification.MediaStyle();
        mMediaStyle.setShowActionsInCompactView(0, 1, 2);
        mMediaBuilder.setStyle(mMediaStyle);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 如果Id 一样可以更新通知
        mNotificationManager.notify(1, mMediaBuilder.build());
    }
8. 自定义通知内容

实现效果

实现代码

    /**
     * 自定义样式通知
     * **/
    public void NotificationCustomView(View view) {

        /***
         * 自定义Remoteview
         * **/
        RemoteViews remoteViews = new RemoteViews(getPackageName(),
                R.layout.notification_view);
        remoteViews.setTextViewText(R.id.tv_content_title, "十年");
        remoteViews.setTextViewText(R.id.tv_content_text, "陈奕迅");
        // 打开上一首
        remoteViews.setOnClickPendingIntent(R.id.btn_pre,
                SetClickPendingIntent(NOTIFICATION_PRE));
        // 打开下一首
        remoteViews.setOnClickPendingIntent(R.id.btn_next,
                SetClickPendingIntent(NOTIFICATION_NEXT));
        // 点击整体布局时,打开播放器
        remoteViews.setOnClickPendingIntent(R.id.btn_play,
                SetClickPendingIntent(NOTIFICATION_PLAY));
        // 点击整体布局时,打开Activity
        remoteViews.setOnClickPendingIntent(R.id.ll_root,
                SetClickPendingIntent(NOTIFICATION_ACTIVITY));

        remoteViews.setOnClickPendingIntent(R.id.img_clear,
                SetClickPendingIntent(NOTIFICATION_CANCEL));

        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker("当前正在播放..")
                .setWhen(System.currentTimeMillis())
                .setContentTitle("十年")
                .setContentText("陈奕迅")
                .setAutoCancel(true)
                .setLargeIcon(
                        DrawableUtils.DrawableToBitmap(getResources()
                                .getDrawable(R.drawable.ic_launcher)))
                .setContent(remoteViews);

        Utils.mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 打开通知
        Utils.mNotificationManager.notify(Utils.NOTIFICATION_CUSTOM_ID,
                builder.build());
    }

    public PendingIntent SetClickPendingIntent(int what) {
        switch (what) {

        case NOTIFICATION_PRE:
            Intent intentPre = new Intent(this, MainActivity.class);
            intentPre.putExtra("cmd", what);
            int flagPre = PendingIntent.FLAG_UPDATE_CURRENT;
            PendingIntent clickPreIntent = PendingIntent.getActivity(this,
                    what, intentPre, flagPre);
            return clickPreIntent;

        case NOTIFICATION_PLAY:
            Intent intentPlay = new Intent(this, NotificationMethods.class);
            intentPlay.putExtra("cmd", what);
            int flagPlay = PendingIntent.FLAG_UPDATE_CURRENT;
            PendingIntent clickPlayIntent = PendingIntent.getActivity(this,
                    what, intentPlay, flagPlay);
            return clickPlayIntent;
        case NOTIFICATION_NEXT:
            Intent intentNext = new Intent(this, ActivityMethods.class);
            intentNext.putExtra("cmd", what);
            int flagNext = PendingIntent.FLAG_UPDATE_CURRENT;
            PendingIntent clickNextIntent = PendingIntent.getActivity(this,
                    what, intentNext, flagNext);
            return clickNextIntent;
        case NOTIFICATION_ACTIVITY:
            Intent intentActivity = new Intent(this, ServiceMethod.class);
            intentActivity.putExtra("cmd", what);
            int flag = PendingIntent.FLAG_UPDATE_CURRENT;
            PendingIntent clickIntent = PendingIntent.getActivity(this, what,
                    intentActivity, flag);
            Toast.makeText(getApplicationContext(), "打开Activity", 0).show();
            return clickIntent;
        case NOTIFICATION_CANCEL:

            Intent intentCancel = new Intent("Notification_cancel");
            intentCancel.putExtra("cancel_notification_id",
                    Utils.NOTIFICATION_CUSTOM_ID);
            int flagCancel = PendingIntent.FLAG_CANCEL_CURRENT;
            PendingIntent clickCancelIntent = PendingIntent.getBroadcast(this,
                    0, intentCancel, flagCancel);
            return clickCancelIntent;
        default:
            break;
        }
        return null;

    }

自定View 布局如下:




    

    

        

        
    

    

实现自定义通知删除按钮事件实现

        case NOTIFICATION_CANCEL:

            Intent intentCancel = new Intent("Notification_cancel");
            intentCancel.putExtra("cancel_notification_id",
                    Utils.NOTIFICATION_CUSTOM_ID);
            int flagCancel = PendingIntent.FLAG_CANCEL_CURRENT;
            PendingIntent clickCancelIntent = PendingIntent.getBroadcast(this,
                    0, intentCancel, flagCancel);
            return clickCancelIntent;
注意

广播是四大组件之一,需要在AndroidManfest.xml 中注册

注册方式如下:

        
            
                
                
                
                
            
        

至此,本篇已结束,如有不对的地方,欢迎您的建议与指正。同时期待您的关注,感谢您的阅读,谢谢!

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/75842.html

相关文章

  • Service 使用详解

    摘要:只能执行单一操作,无法返回结果给调用方,常用于网络下载上传文件,播放音乐等。绑定模式此模式通过绑定组件等调用启动此服务随绑定组件的消亡而解除绑定。 showImg(https://segmentfault.com/img/remote/1460000019975019?w=157&h=54); 极力推荐文章:欢迎收藏Android 干货分享 showImg(https://segme...

    freewolf 评论0 收藏0
  • Broadcast 使用详解

    摘要:静态注册广播的方法动态注册广播在中动态注册广播,通常格式如下动态注册广播动态注册监听灭屏点亮屏幕的广播在广播中动态注册广播请注意一定要使用,防止为空,引起空指针异常。绑定模式此模式通过绑定组件等调用启动此服务随绑定组件的消亡而解除绑定。 showImg(https://segmentfault.com/img/remote/1460000019975019?w=157&h=54); 极...

    Y3G 评论0 收藏0
  • Android四大组件之Service全解析

    摘要:四大组件都支持这个属性。到目前为止,中总共有三种启动方式。返回值方法有一个的返回值,这个返回值标识服务关闭后系统的后续操作。,启动后的服务被杀死,不能保证系统一定会重新创建。 1. 简介 这篇文章会从Service的一些小知识点,延伸到Android中几种常用进程间通信方法。 2. 进程        Service是一种不提供用户交互页面但是可以在后台长时间运行的组件,可以通过在An...

    alaege 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<