关于新版本的Notification的用法

来源:互联网 发布:vim怎么编程 编辑:程序博客网 时间:2024/05/29 09:26


 今天在做Android 4.3下的前台服务方面的开发时,使用到了Notification这个类。使用的过程中发现使用以前的一些例子中用的构造方法和setLatestEventInfo()方法时,Eclipse却出现了警告:“ 不建议使用类型 Notification 的Notification(icon, tickerText, when)构造方法和 setLatestEventInfo(Context, CharSequence, CharSequence, PendingIntent)方法”!

经过一番查询,总结一下notification在各个版本中的用法:

1.低于API Level 11版本,也就是Android 2.3.3以下的系统中,setLatestEventInfo()函数是唯一的实现方法。

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);Notification notification = new Notification(R.drawable.ic_launcher, "This is ticker text",System.currentTimeMillis());Intent intent = new Intent(this, NotificationActivity.class);PendingIntent pi = PendingIntent.getActivity(this, 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);notification.setLatestEventInfo(this, "This is content title","This is content text", pi);                        manager.notify(1, notification);

2. 高于API Level 11,低于API Level 16 版本中,可使用Notification.Builder来构造函数。但要使用getNotification()来使notification实现。此时,前面版本在notification中设置的Flags,icon等属性要在builder里面设置。

Notification.Builder builder = new Notification.Builder(context)              .setAutoCancel(true)              .setContentTitle("title")              .setContentText("describe")              .setContentIntent(pendingIntent)              .setSmallIcon(R.drawable.ic_launcher)              .setWhen(System.currentTimeMillis())              .setOngoing(true);  notification=builder.getNotification(); 

3.高于API Level 16的版本,就可以用Builder和build()函数来配套的方便使用notification了。

Notification notification = new Notification.Builder(context)             .setAutoCancel(true)             .setContentTitle("title")             .setContentText("describe")             .setContentIntent(pendingIntent)             .setSmallIcon(R.drawable.ic_launcher)             .setWhen(System.currentTimeMillis())             .build();   

注意:高版本中对应的方法不能在低版本中使用,否则会报类似的版本错误:

Android Call requires API level 11 (current min is 8)的解决方案

相应的解决办法是: 如果把manifest文件中的user-sdk的android:minSdkVersion改为报错的那个高版本就没事。比如下面:

<uses-sdk        android:minSdkVersion="11"   //这个之前是8        android:targetSdkVersion="17" />


0 0
原创粉丝点击