android5.0使用Notification报RemoteServiceException的解决办法

有时android5.0下使用Notification会报如下错误信息(比如开启重启动系统就要发送通知)

android.app.RemoteServiceException:Badnotificationpostedfrompackage*:Couldn'tcreateicon:StatusBarIcon

这个问题多数集中在setSmallIcon(R.drawable.scanner_small)这句代码上,在某些情况下(比如开启重启动系统就要发送通知),R.drawable.scanner_small这个资源尚未准备好,导致了App异常。那怎么办呢?

这是android5.0的bug,在android4.4和6.0中都正常,一般情况下,这没办法解决,如老外说的那样

http://stackoverflow.com/questions/25317659/how-to-fix-android-app-remoteserviceexception-bad-notification-posted-from-pac

不过,如果你不介意图标大小,可以这样写:

setSmallIcon(context.getApplicationInfo().icon)

从ApplicationInfo中拿到应用icon当作SmallIcon。

总之,要抢在系统重启动之前拿到icon,而不至于拿到一个空的resId。

解决思路:

http://stackoverflow.com/questions/24968556/how-to-fix-this-bug-android-app-remoteserviceexception-bad-notification-post

附上我完整的Notification代码

private static final int NOTIFY_ID = 0;
	public static void showCustomNotification(Context context) {
		NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		Intent intent = new Intent(context, MainActivity.class);
//		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// FLAG_ONE_SHOT
		intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
		NotificationCompat.Builder mBuilder = new Builder(context);
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.custom_notify);
        
        boolean isScan=(Boolean)SPUtils.get(context, App.KEY_SCAN, true);
        remoteViews.setTextViewText(R.id.btn_scan,isScan?"隐藏扫描键": "显示扫描键");
        //点击事件处理
        Intent actionIntent = new Intent(App.ACTION_NOTIFICATION);
        actionIntent.putExtra(App.KEY_NOTIFICATION_CLICK, isScan);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.btn_scan, pendingIntent);
        mBuilder.setContent(remoteViews)
                .setContentIntent(contentIntent)
                .setTicker("扫描精灵")
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setSmallIcon(context.getApplicationInfo().icon)//采用quick fallback image
				.setDefaults(Notification.DEFAULT_ALL);
        
        Notification notify = mBuilder.build();
        notify.flags = Notification.FLAG_NO_CLEAR;//|Notification.FLAG_ONGOING_EVENT;
        notificationManager.notify(NOTIFY_ID, notify);
	}

相关推荐