【问题标题】:Exception while creating an Android Notification创建 Android 通知时出现异常
【发布时间】:2015-07-09 03:04:07
【问题描述】:

在我的应用程序中,我使用以下代码构造了一个通知:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder notificationBuilder = new Notification.Builder(this)
    .setSmallIcon(R.drawable.ic_notify_nursing)
    .setOngoing(true)
    .setContentTitle(getString(R.string.feeding_in_progress));

if(android.os.Build.VERSION.SDK_INT >= 21) {
    notificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
}

Intent resultIntent = new Intent(this, MainActivity.class);

PendingIntent resultPendingIntent = PendingIntent.getActivity( this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(resultPendingIntent);

if(android.os.Build.VERSION.SDK_INT >= 16) {
    notificationManager.notify(NOTIFICATION_TAG, NOTIFICATION_ID, notificationBuilder.build());
} else {
    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.getNotification());
}

在 Google Play 控制台中,我看到此行记录了许多异常:

notificationManager.notify(NOTIFICATION_TAG, NOTIFICATION_ID, notificationBuilder.build());

该错误主要发生在 Android 5.0 和 5.1 中,旧版本没有问题。堆栈跟踪看起来像:

java.lang.ArrayIndexOutOfBoundsException: src.length=0 srcPos=0 dst.length=1 dstPos=0 length=1
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3326)
    at android.app.ActivityThread.access$2200(ActivityThread.java:178)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1547)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:145)
    at android.app.ActivityThread.main(ActivityThread.java:5944)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
    Caused by: java.lang.ArrayIndexOutOfBoundsException: src.length=0 srcPos=0 dst.length=1 dstPos=0 length=1
    at java.lang.System.arraycopy(System.java:358)
    at android.util.ArrayMap.putAll(ArrayMap.java:579)
    at android.os.Bundle.putAll(Bundle.java:183)
    at android.app.Notification$Builder.build(Notification.java:3786)

有什么想法吗?

【问题讨论】:

    标签: android android-notifications


    【解决方案1】:

    根据notification guide list of required fields,您必须通过setContentText() 方法设置内容文本。请注意,这可以为空,但需要设置。

    【讨论】:

      【解决方案2】:

      使用 NotificationCompat.Builder 来简化您的代码并避免意外。

      【讨论】:

        【解决方案3】:

        看起来该方法在 API 11 中已被弃用,如下所述..

        Issue with Notification Manager on android

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-29
          • 2015-03-22
          • 1970-01-01
          相关资源
          最近更新 更多