Android使用通知

来源:互联网 发布:淘宝下拉框软件 编辑:程序博客网 时间:2024/06/16 15:10

首先是获取NotificationManager的实例:

NotificationManager manager = (NotificationManger) getSystemService(Content.NOTIFICATION_SERVICE);

然后用一个Builder构造器来创建Notification对象:

Notification notification = new NofiticationCompat.Builder().builder;//空的notification对象

可以这样:

Notification notification = new NofiticationCompat.Builder()

              .setContentTile(" ")//设置通知名称

              .setContentText(" ");//设置通知内容

              .setWhen(System.CurrentTimeMillis())//显示通知发出时间

              .setSmallIcon(R.drawable.small_icon)//设置通知显示在状态栏上的小图标

              .setBigIcon(BitmapFactory.decodeResource(getResources(),R.drawable.large_icon))//............大图标


发送一个通知的Button:

    @Override    public void onClick(View view) {        switch (view.getId()){            case R.id.send_notice:                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);                Notification notification = new NotificationCompat.Builder(this)                        .setContentTitle("This is content title")                        .setContentText("This is content text")                        .setWhen(System.currentTimeMillis())                        .setSmallIcon(R.mipmap.ic_launcher)                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))                        .build();                manager.notify(1,notification);                break;            default:                break;        }    }

设置通知的点击效果:

新建一个通知的活动NotificationActivity:

                Intent intent = new Intent(this,NotificationAcitivity.class);                PendingIntent  pi = PendingIntent.getActivity(this,0,intent,0);

然后再在实例化notification的时候加入.setContentIntent(pi);

设置点击后取消通知:

①在实例化notification的时候加入.setAutoCancel(true)   

②在Notification OnCreate()中加入代码:

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);        manager.cancel(1);//1是指的这条通知的id


更多通知效果:

.setSound(Uri.fromFile(new File("路径"))) 通知时播放音频

.setVibrate(new long[]{0,1000,2000,3000}) 设置通知时震动 0表示静止0ms 1000表示震动1000ms 2000表示静止2000ms 3000表示又震动3000ms 以此类推

震动的权限声明: <uses-permission android.name="android.permission.VIBRATE">

.setLights(Color.GREEN,1000,1000) 设置LED灯 第一个参数是颜色,第二个是亮的时长,第三个是暗的时长

.setDefaults(NotificationCompat.DEFAULT_ALL) 设置默认效果 这里是全部默认

通知的高级功能:

设置长文本的text

.setStyle(NotificationCompat.BigTextStyle().bigText("Learn how to build notifications, send and sync data, and use voice actions.Get the officical Android IDE and developer tools to build apps for android."))

插入图片

.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)))

设置通知的重要程度

.setPriority(NotificationCompat.PRIORITY_MAX)  这里把通知的重要级设置为最高


原创粉丝点击