Android 通知使用小结

**

通知Notification

**
**

一、通知的基本使用

**
1)使用v4包里的NotificationCompat.Builder构建器来构建通知.

第一步:实例化通知栏构造器NotificationCompat.Builder

创建通知的构建器对象:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

第二步:对Builder进行配置

设置标题:builder.setContentTitle(“通知”);

设置提示:builder.setContentText(“下雨了”);

设置通知小图标必须要):builder.setSmallIcon(R.drawable.ic_launcher);

设置数量:builder.setNumber(3);

设置收到通知提示可以是声音、灯光、震动,其中震动DEFAULT_VIBRATE 需要权限: builder.setDefaults(Notification.DEFAULT_VIBRATE);

设置为正在运行:builder.setOngoing(true);

第三步:获取状态通知栏管理

得到通知管理对象(属于系统服务):
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

得到通知对象:Notification notification = builder.build();

第四步:通过通知管理对象发送通知

发送通知:manager.notify((int)System.currentTimeMillis(), notification);(如果id相同,即使发送多个通知,也只显示一个)

删除一个特定的通知ID对应的通知:
mNotificationManager.cancel(notifyId);

删除所有通知:mNotificationManager.cancelAll();

注意:1)通知必须设置icon,不然会报错
2)最好使用NotificationCompat.Builder构建器来创建通知


**

二.通知的高级使用

**
PendingIntent简介:
官方文档:
A description of an Intent and target action to perform with it. Instances of this class are created with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), getService(Context, int, Intent, int); the returned object can be handed to other applications so that they can perform the action you described on your behalf at a later time.
简单来说PendingIntent的作用就是描述intent并执行intent。

1)什么是PendingIntent
PendingIntent和Intent略有不同,它可以设置执行次数,主要用于远程服务通信、闹铃、通知、启动器、短信中,在一般情况下用的比较少。
2)PendingIntent什么用
Notification支持多种Intent来响应单击事件、消除事件、处理紧急状态的全屏事件等。
这里就用到了setContentIntent(PendingIntent intent)来处理以上这么多的事件。
3)相关属性和方法
属性:
PendingIntent的位标识符:
FLAG_ONE_SHOT 表示返回的PendingIntent仅能执行一次,执行完后自动取消
FLAG_NO_CREATE 表示如果描述的PendingIntent不存在,并不创建相应的PendingIntent,而是返回NULL
FLAG_CANCEL_CURRENT 表示相应的PendingIntent已经存在,则取消前者,然后创建新的PendingIntent,这个有利于数据保持为最新的,可以用于即时通信的通信场景
FLAG_UPDATE_CURRENT 表示更新的PendingIntent

2.1如点击通知跳到一个activity:

Intent intent = new Intent(this,MainActivity.class);
//可以当通知被点击时自动执行 startActiivty()
PendingIntent pending = PendingIntent.getActivity(this, 6, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(pending);
builder.setAutoCancel(true);//设置点击通知自动消失

2.2自定义布局的通知
使用自定义布局时需要用到.

/**
     * 显示自定义布局通知
     */
    public void showSelfDefNotify(){
        //先设定RemoteViews
        RemoteViews view_custom = new RemoteViews(getPackageName(), R.layout.view_custom);
        //设置对应IMAGEVIEW的ID的资源图片
        view_custom.setImageViewResource(R.id.custom_icon, R.drawable.beer);
        view_custom.setTextViewText(R.id.tv_custom_title, "小熊搜搜");
        view_custom.setTextViewText(R.id.tv_custom_content, "大事不好,房子要倒!");
        mBuilder = new Builder(this);
        mBuilder.setContent(view_custom)
                .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))
                .setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示
                .setTicker("有新资讯")
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                .setOngoing(false)//不是正在进行的   true为正在进行  效果和.flag一样
                .setSmallIcon(R.drawable.beer);
        Notification notify = mBuilder.build();
        notify.contentView = view_custom;
        mNotificationManager.notify(notifyId, notify);
    }

2.3带按钮的的自定义布局,类似听音乐时的通知栏
布局实现如上,按钮点击事件通过广播来传递。

/**
     * 带按钮的通知栏
     */
    public void showButtonNotify(){
        NotificationCompat.Builder mBuilder = new Builder(this);
        RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.view_custom_button);
        mRemoteViews.setImageViewResource(R.id.custom_song_icon, R.drawable.sing_icon);
        //API3.0 以上的时候显示按钮,否则消失
        mRemoteViews.setTextViewText(R.id.tv_custom_song_singer, "周杰伦");
        mRemoteViews.setTextViewText(R.id.tv_custom_song_name, "听妈妈的话");
        //如果版本号低于(30),那么不显示按钮
        if(BaseTools.getSystemVersion() <= 9){
            mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.GONE);
        }else{
            mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.VISIBLE);
            //
            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(INTENT_BUTTONID_TAG, BUTTON_PREV_ID);
        //这里加了广播,所及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(INTENT_BUTTONID_TAG, BUTTON_PALY_ID);
        PendingIntent intent_paly = PendingIntent.getBroadcast(this, 2, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_play, intent_paly);
        /* 下一首 按钮  */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_NEXT_ID);
        PendingIntent intent_next = PendingIntent.getBroadcast(this, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);   mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_next, intent_next);
        mBuilder.setContent(mRemoteViews)
    .setContentIntent(getDefalutIntent(Notification.FLAG_ONGOING_EVENT))
                .setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示
                .setTicker("正在播放")
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                .setOngoing(true)
                .setSmallIcon(R.drawable.sing_icon);
        Notification notify = mBuilder.build();
        notify.flags = Notification.FLAG_ONGOING_EVENT;
        mNotificationManager.notify(200, notify);
    }

2.4在通知栏显示一个下载进度的通知
主要是通过builder.setProgress(max, current, false);方法实现进度显示的。

这里模拟下载一张图片:

@Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            if (params[0] != null) {
                imageUrl = params[0];
                try {
                    URL url = new URL(imageUrl);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.setDoInput(true);
                    conn.connect();
                    int currentLen = 0;
                    InputStream inputStream = null;
                    ByteArrayOutputStream bos = null;
                    if (conn.getResponseCode() == 200) {
                        inputStream = conn.getInputStream();
                        totalLen = conn.getContentLength();
                        bos = new ByteArrayOutputStream();
                        byte[] arr = new byte[1024];
                        int len = 0;
                        while ((len = inputStream.read(arr)) != -1) {
                            bos.write(arr, 0, len);
                            currentLen += len;
                            publishProgress(currentLen);
                            Thread.sleep(500);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                byte[] buffer = null;
                try {
                    buffer = getDataBytes(imageUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 在后台开始下载图片
                bitmap = BitmapFactory
                        .decodeByteArray(buffer, 0, buffer.length);
            }
            return bitmap;
        }

--------不断刷新进度----------
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            builder.setProgress(totalLen, values[0], false);
            if (totalLen == values[0]) {
                builder.setOngoing(false);
                builder.setContentText("下载完成");
            }
            Notification notification = builder.build();
            notificationManager.notify(1, notification);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null && imageView != null)
                imageView.setImageBitmap(bitmap);
        }

3.显示自定义布局的Toast
1)自定义一个toast显示布局
2)在程序中得到toast对象,并设置显示布局和显示位置

Toast toast = new Toast(this);      
        View view = getLayoutInflater().inflate(R.layout.toast_layout, null);       
        toast.setView(view);//设置吐司使用的布局     
        toast.setGravity(Gravity.CENTER, 0,0);//设置吐司的显示位置
        toast.setDuration(Toast.LENGTH_SHORT);      
        toast.show();

以上实例源码

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值