创建Android通知时出现异常

时间:2015-07-08 18:12:44

标签: android android-notifications

在我的应用程序中,我使用以下代码构建通知:

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)

这里有什么想法?

3 个答案:

答案 0 :(得分:1)

根据notification guide list of required fields,您必须通过setContentText()方法设置内容文字。请注意,这可能是空白的,但需要进行设置。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

从API 11开始,该方法似乎已被弃用,如下所述。

Issue with Notification Manager on android