通知代码在sdkVersion 16下无效

时间:2013-11-19 20:42:29

标签: java android sdk notifications

我写了这个方法

private void showVocNotification(String FR, String DE, String Language) {
String kleinerText = DE + "\nheißt auf " + Language + "\n" + FR; 
String grosserText = "Merk dir das für immer und ewig";


Intent i = new Intent(this, Remind.class);
i.setAction("de.bsv.taubenNotification");


PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);    

Notification notification  = new Notification.Builder(this)
.setContentTitle(grosserText)
.setStyle(new Notification.BigTextStyle().bigText(kleinerText)) 
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(contentIntent)
.setAutoCancel(true).build();

NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNM.notify("dashierIstdieID", 0, notification);
Log.d(Log_TAG, "Notified");
}

问题是,它需要android:minSdkVersion =“16”(API级别16)。您可能知道,许多手机仍在运行Android 2.3或4.0。

我需要更改代码,可以运行至少API级别为9的应用程序。

这是你的一部分,因为我没有找到替代方案,或者如果你找到了什么,我也会对解释链接感到非常高兴。

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用NotificationCompat类而不是通知。您可以在兼容性库中找到它,并将为您处理所有兼容性/遗留的东西。它的Builder与Notification.Builder具有完全相同的用法

答案 1 :(得分:0)

试试这个:

private void generateNotification(Context context, String message) {

int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, myactivity.class), 0);

// To support 2.3 os, we use "Notification" class and 3.0+ os will use
// "NotificationCompat.Builder" class.
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(icon, message, 0);
notification.setLatestEventInfo(context, appname, message,
    contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);

} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
    context);
notification = builder.setContentIntent(contentIntent)
    .setSmallIcon(icon).setTicker(appname).setWhen(0)
    .setAutoCancel(true).setContentTitle(appname)
    .setContentText(message).build();

notificationManager.notify(0 , notification);
}
}

希望这有帮助。