【21】Notification

一、什么是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的布局,可以自己加按钮什么的。但是高级的控件是不支持的。




    


    

    




        

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;
    }
}

以下为自定义控件代码。




    

    

        

        

        
    

    

        

        
    


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

你可能感兴趣的:(【21】Notification)