在BroadcastReceiver中使用通知
BroadcastReceiver通常需要向用户传达发生的某件事或状态,可以使用通知栏通知提醒用户。
创建通知的过程:
1、创建一个合适的通知
2、获得通知管理器的权限
3、向通知管理器发送通知
创建通知时,需要包含以下几个部分:
1、要显示的图标
2、显示的提示文本
3、传送它的时间
然后使用Context获取一个名为Context.NOTIFICATION_SERVICE的系统服务来获取到通知管理器,如下所示:
//Get the notification manager String ns = Context.NOTIFICATION_SERVICE; NotificationManager nm = (NotificationManager)ctx.getSystemService(ns);
下面看一个例子
对应的广播接收者定义如下
public class NotificationReceiver extends BroadcastReceiver { private static final String tag = "Notification Receiver"; @Override public void onReceive(Context context, Intent intent) { Utils.logThreadSignature(tag); Log.d(tag, "intent=" + intent); String message = intent.getStringExtra("message"); Log.d(tag, message); this.sendNotification(context, message); } private void sendNotification(Context ctx, String message) { //Get the notification manager String ns = Context.NOTIFICATION_SERVICE; NotificationManager nm = (NotificationManager)ctx.getSystemService(ns); //Create Notification Object int icon = R.drawable.robot; CharSequence tickerText = "Hello"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); //Set ContentView using setLatestEvenInfo Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.google.com")); PendingIntent pi = PendingIntent.getActivity(ctx, 0, intent, 0); notification.setLatestEventInfo(ctx, "title", "text", pi); //Send notification //The first argument is a unique id for this notification. //This id allows you to cancel the notification later nm.notify(1, notification); } }
该BroadcastReceiver接收通知后,创建系统通知显示在通知栏。当点击通知栏的通知时,打开浏览器,访问google.com