美文网首页
【21】Notification

【21】Notification

作者: 嗟嗟嗟 | 来源:发表于2016-07-12 09:55 被阅读0次

一、什么是Notification?

是可以常驻在通知栏上的一种通知。可设置按钮来控制程序。

二、为什么要使用Notification?

对于需要常驻的应用,可通过通知栏来方便操作程序,还可以提醒一些重要事项。

三、如何使用?

贴下简单的音乐服务使用方法,使用系统默认的方式

public class MyService extends Service {

    private NotificationManager mNotificationManager;

    @Override
    public void onCreate() {
        super.onCreate();

        //第一步:获取状态通知栏管理
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //第二步:实例化通知栏构造器NotificationCompat.Builder
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        //第三步:对Builder进行配置
        mBuilder.setContentTitle("测试标题")//设置通知栏标题
                .setContentText("测试内容") //设置通知栏点击意图
            //  .setNumber(number) //设置通知集合的数量
                .setTicker("测试通知来啦") //通知首次出现在通知栏,带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间
//                .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
            //  .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setOngoing(false)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合
                //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
                .setSmallIcon(R.mipmap.ic_launcher);//设置通知小ICON

        //点击跳转
        Intent intent = new Intent(this,MainActivity.class);
        //加载意图
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        mBuilder.setContentIntent(pendingIntent);


        //更新通知
        mNotificationManager.notify(1, mBuilder.build());


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消通知
        mNotificationManager.cancel(1);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

代码中又比较详细的注释就不多说了。
此服务启动后即会自动生成一个通知。

下面说下如何自定义通知:

首先需要自己定义一个XML的布局,可以自己加按钮什么的。但是高级的控件是不支持的。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/notification_image_view"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:src="@mipmap/ic_launcher"
        android:layout_width="64dp"
        android:layout_height="64dp" />


    <TextView
        android:id="@+id/notification_text_view"
        android:layout_toRightOf="@+id/notification_image_view"
        android:layout_toLeftOf="@+id/notification_lin"
        android:layout_centerVertical="true"
        android:text="sun_da_shen111111111111"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:id="@+id/notification_lin"
        android:layout_centerVertical="true"
        android:orientation="horizontal"
        android:layout_alignParentRight="true"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content">




        <Button
            android:id="@+id/notification_pre"
            android:text="上一首"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/notification_play"
            android:text="播放"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/notification_next"
            android:text="下一首"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


    </LinearLayout>


</RelativeLayout>

PS:一般标准通知的高度为64dp,宽度为屏幕的宽度,控件不要超过这个尺寸。

然后跟系统默认的设置类似,所不同的是需要自定义RemoteViews,先绑定自己写的XML文件,再通过mRemoteViews.set的方法设置自定义控件的属性,最后通过PendingIntent.getBroadcast()方法发送广播来传递消息,消息需要广播接收器来接受。

此代码为一个简单的音乐播放器代码

public class MyService extends Service {


    public static final String ACTION_BUTTON = "intent_action";
    private MediaPlayer mediaPlayer;
    private NotificationManager mNotificationManager;

    private ButtonBroadcastReceiver bReceiver;
    Boolean isPlay = true;

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        mediaPlayer = MediaPlayer.create(MyService.this,R.raw.sun_da_shen);
        mediaPlayer.start();

        initButtonReceiver();


        showButtonNotify();


    }

    public void showButtonNotify() {
        //第一步:获取状态通知栏管理
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //第二步:实例化通知栏构造器NotificationCompat.Builder
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        //第三步:对Builder进行配置
        RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.view_custom_button);
        mRemoteViews.setImageViewResource(R.id.custom_song_icon, R.drawable.sing_icon);
        //API3.0 以上的时候显示按钮,否则消失
        mediaPlayer.getTrackInfo();
        mRemoteViews.setTextViewText(R.id.tv_custom_song_singer, "周杰伦");
//        mRemoteViews.setTextColor(R.id.);
        mRemoteViews.setTextViewText(R.id.tv_custom_song_name, "七里香");


        if(isPlay){
            mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.drawable.btn_pause);
        }else{
            mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.drawable.btn_play);
        }


        //点击的事件处理
        Intent buttonIntent = new Intent(ACTION_BUTTON);
        /* 上一首按钮 */
        buttonIntent.putExtra("ButtonId", 1);
        //这里加了广播,所及INTENT的必须用getBroadcast方法
        PendingIntent intent_prev = PendingIntent.getBroadcast(this, 1, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_prev, intent_prev);
        /* 播放/暂停  按钮 */
        buttonIntent.putExtra("ButtonId", 2);
        PendingIntent intent_paly = PendingIntent.getBroadcast(this, 2, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_play, intent_paly);
        /* 下一首 按钮  */
        buttonIntent.putExtra("ButtonId", 3);
        PendingIntent intent_next = PendingIntent.getBroadcast(this, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_next, intent_next);

        //点击跳转
        Intent intent = new Intent(this,MainActivity.class);
//        Notification notify = mBuilder.build();
//        notify.flags = Notification.FLAG_ONGOING_EVENT;
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        mBuilder.setContent(mRemoteViews)
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示
                .setTicker("正在播放")
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                .setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher);

        //会报错,还在找解决思路
//      notify.contentView = mRemoteViews;
//      notify.contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
        mNotificationManager.notify(1, mBuilder.build());

    }

    /** 带按钮的通知栏点击广播接收 */
    public void initButtonReceiver(){
        bReceiver = new ButtonBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_BUTTON);
        registerReceiver(bReceiver, intentFilter);
    }

    /**
     *   广播监听按钮点击时间
     */
    public class ButtonBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if(action.equals(ACTION_BUTTON)){
                //通过传递过来的ID判断按钮点击属性或者通过getResultCode()获得相应点击事件
                int buttonId = intent.getIntExtra("ButtonId", 0);
                switch (buttonId) {
                    case 1:
                        Log.d("ButtonId" , "上一首");
                        Toast.makeText(getApplicationContext(), "上一首", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        String play_status = "";
                        isPlay = !isPlay;
                        if(isPlay){
                            play_status = "开始播放";
                            mediaPlayer.start();
                        }else{
                            play_status = "已暂停";
                            mediaPlayer.pause();
                        }
                        showButtonNotify();
                        Log.d("ButtonId" , play_status);
                        Toast.makeText(getApplicationContext(), play_status, Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Log.d("ButtonId" , "下一首");
                        Toast.makeText(getApplicationContext(), "下一首", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bReceiver!=null){
            unregisterReceiver(bReceiver);
        }
        mediaPlayer.stop();
        mNotificationManager.cancel(1);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_NOT_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

以下为自定义控件代码。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/custom_song_icon"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:src="@drawable/sing_icon" />

    <LinearLayout
        android:id="@+id/ll_custom_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dip"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/btn_custom_prev"
            style="@style/btn_custom_style"
            android:src="@drawable/btn_prev" />

        <ImageButton
            android:id="@+id/btn_custom_play"
            style="@style/btn_custom_style"
            android:contentDescription="播放"
            android:src="@drawable/btn_play" />

        <ImageButton
            android:id="@+id/btn_custom_next"
            style="@style/btn_custom_style"
            android:contentDescription="下一首"
            android:src="@drawable/btn_next" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginBottom="5dip"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="5dip"
        android:layout_toLeftOf="@id/ll_custom_button"
        android:layout_toRightOf="@id/custom_song_icon"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_custom_song_singer"
            style="@style/NotificationTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="title"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/tv_custom_song_name"
            style="@style/NotificationContent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:text="content"
            android:textSize="12sp" />
    </RelativeLayout>

</RelativeLayout>

参考文档
http://blog.csdn.net/wa991830558/article/details/39315939

相关文章

  • 【21】Notification

    一、什么是Notification? 是可以常驻在通知栏上的一种通知。可设置按钮来控制程序。 二、为什么要使用No...

  • 2018-09-25

    2018-11-12 00:10:21 +0900 Notification Display is turned ...

  • 笔记49 | Android通讯之Notification[转]

    地址 目录 Notification 概述 Notification 的基本操作 创建 Notification ...

  • 通知

    Android中Notification 提示对话框,notification 概述 notification,俗...

  • Notification框架简介

    目录 Notification介绍 Notification框架原理 Notification框架服务端启动过程 ...

  • Androd Notification

    The Guide Notification Notification Builder NotificationM...

  • notification

    notification文档 桌面通知 notification 示例

  • Notification详解

    Notification详解 Notification的使用步骤 自定义Notification样式 自定义Not...

  • Notification 总结

    Notification Notification 能干什么,那些设计是和Notification相关的;这里直接...

  • Android Notification的使用

    Notification的作用 能够在通知栏展示一些信息 Notification介绍 notification-...

网友评论

      本文标题:【21】Notification

      本文链接:https://www.haomeiwen.com/subject/qbgjjttx.html