1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| package com.example.mbenben.newstudy; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.view.View; public class MainActivityextends Activity { private NotificationManagernotificationManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.click).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showNotifaction(); } }); findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { cancelNotifacation(); } }); } private void showNotifaction(){ NotificationCompat.Builder builder =new NotificationCompat.Builder(this); builder.setTicker("通知栏提示"); builder.setSmallIcon(R.mipmap.ic_launcher);//设置通知 栏小图标 builder.setContentTitle("通知栏标题");//标题 builder.setContentText("通知栏内容");//内容 builder.setWhen(System.currentTimeMillis());//设置时间 这里设置的系统默认时间 // 设置以下三个需要对应权限 // builder.setDefaults(Notification.DEFAULT_SOUND);//设置提示音 // builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置指示灯 // builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置震动 builder.setDefaults(Notification.DEFAULT_ALL);//提示音,指示灯,震动同样需要3种对应权限 // 设置通知点击事件PendingIntent Intent intent =new Intent(); // PendingIntent.getActivity(上下文对象, 请求码, intent, 0) // 第一个参数连接上下文的context // 第二个参数是对PendingIntent的描述,请求值不同Intent就不同 // 第三个参数是一个Intent对象,包含跳转目标 // 第四个参数有4种状态 // FLAG_CANCEL_CURRENT:如果当前系统中已经存在一个相同的PendingIntent对象,那么就将先将已有的PendingIntent取消,然后重新生成一个PendingIntent对象。 // FLAG_NO_CREATE:如果当前系统中不存在相同的PendingIntent对象,系统将不会创建该PendingIntent对象而是直接返回null。 // FLAG_ONE_SHOT:该PendingIntent只作用一次。在该PendingIntent对象通过send()方法触发过后,PendingIntent将自动调用cancel()进行销毁,那么如果你再调用send()方法的话,系统将会返回一个SendIntentException。 // FLAG_UPDATE_CURRENT:如果系统中有一个和你描述的PendingIntent对等的PendingInent,那么系统将使用该PendingIntent对象,但是会使用新的Intent来更新之前PendingIntent中的Intent对象数据,例如更新Intent中的Extras。 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); builder.setContentIntent(pendingIntent); Notification build = builder.build();//4.1以上 // 拿到通知控制类 notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // 发送通知 notificationManager.notify(自定义一个ID,Notification); notificationManager.notify(1,build); } private void cancelNotifacation(){ // 停止通知 通知的ID notificationManager.cancel(1); } }
|