Android通知

来源:互联网 发布:淘宝网上禁止出售 编辑:程序博客网 时间:2024/05/22 02:01

Android系统原生就有通知功能叫Notification,Notification在Android中显示在顶部状态栏.它有两种显示方法,一种是用系统原生的,另一种是我们自己自定义的.
第一种使用系统的显示通知:

        /**          * 系统通知          */        private void showNotification() {        /**          * Notification有两种创建方式,第一种是通过new可以直接创建,第二种          * 可以通过build来创建.          */        Notification.Builder builder1 = new Notification.Builder(this);        builder1.setSmallIcon(R.drawable.u11); //设置图标        builder1.setContentTitle("标题"); //设置标题        builder1.setContentText("消息内容"); //消息内容        builder1.setWhen(System.currentTimeMillis()); //发送时间        //设置默认提示音,振动方式,灯光                                     builder1.setDefaults(Notification.DEFAULT_ALL);         //打开程序后图标消失        builder1.setAutoCancel(true);        //点击通知跳转到对应的Activity中        Intent intent = new Intent(this, StudyDNAActivity.class);        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);        builder1.setContentIntent(pendingIntent);        Notification notification1 = builder1.build();        mManager.notify(0, notification1); // 通过通知管理器发送通知    }

假如系统的通知不是我们想要的,于是我们就要自己去自定义通知显示的界面:

    /**      * 自定义通知      */    public void defineNotification() {        int icon = R.drawable.u11;//通知显示的图标        long when = System.currentTimeMillis();//通知的事情        Notification notification = new Notification(icon, null, when);        RemoteViews contentView = new RemoteViews(getPackageName(),                        R.layout.custom_notification);//自定义通知的布局        contentView.setImageViewResource(R.id.image, R.drawable.u11);//通知栏显示的图片        contentView.setTextViewText(R.id.text, "通知显示的内容");        notification.contentView = contentView;//设置自己自定义的布局        notification.flags |= Notification.FLAG_AUTO_CANCEL; //点击通知消失        Intent notificationIntent = new Intent(this,StudyDNAActivity.class);        //处理点击通知事件        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,             notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);        notification.contentIntent = pendingIntent;        mManager.notify(0, notification);    }
0 0