有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java通知代码在sdkVersion 16以下不起作用

我写了这个方法

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");
}

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

我需要更改代码,以便可以使用至少9级API运行应用程序

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

多谢各位


共 (2) 个答案

  1. # 1 楼答案

    可以使用NotificationCompat类而不是通知。您可以在兼容性库中找到它,并将为您处理所有兼容性/遗留内容。它的生成器与通知的用法完全相同。建筑商也是

  2. # 2 楼答案

    试试这个:

    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);
    }
    }
    

    希望这有帮助