Notification-使用详解

36次阅读

共计 11336 个字符,预计需要花费 29 分钟才能阅读完成。

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

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

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

  1. Notification 简介
  2. 通知的创建
  3. 通知的管理
  4. 简单的通知
  5. 可以 扩展的通知
  6. 通知中含下载进度条
  7. 通知中含媒体播放控件
  8. 自定义通知内容

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

Notification 简介

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

Notification 继承关系如下:

java.lang.Object
   ↳
    android.app.Notification

1.Notification 简介

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

2. 创建 Notification 的方法

    1. 调用 NotificationCompat.Builder.build() 创建Notification 对象
    1. 然后调用 NotificationManager.notify() Notification 对象传递给系统。

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

    1. 小图标,由 setSmallIcon() 设置
    1. 标题,由 setContentTitle() 设置
    1. 详细文本,由 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. 通知的管理

    1. 更新通知

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

    1. 删除通知

创建时 调用了 setAutoCancel(true)

删除时候调用删除指定ID

NotificationManager.cancel(notificationId)

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

Utils.mNotificationManager.cancelAll();
    1. 在通知中显示进度条

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 布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_root"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#282828"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="8dp" >

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:padding="5dp"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_content_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:textSize="18sp"
            android:text="十年"
            android:textColor="@android:color/white" />

        <TextView
            android:id="@+id/tv_content_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:text="陈奕迅"
            android:textSize="14sp"
           android:textColor="@android:color/white" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_pre"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/music_pre" />

    <Button
        android:id="@+id/btn_play"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:background="@drawable/music_play" />

    <Button
        android:id="@+id/btn_next"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:background="@drawable/music_next" />

    <ImageView
        android:id="@+id/img_clear"
        android:layout_width="30dp"
        android:layout_height="match_parent"
        android:layout_gravity="top|center_horizontal"
        android:padding="6dp"
        android:src="@drawable/clear_img" />

</LinearLayout>

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

        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 中注册

注册方式如下:

        <receiver
            android:name="com.programandroid.BroadcastReceiver.NotificationReceived"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="Notification_cancel" />
                <action android:name="Notification_music_pre" />
                <action android:name="Notification_music_play" />
                <action android:name="Notification_music_next" />
            </intent-filter>
        </receiver>

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

正文完
 0