Android 7.0及以上版本上传应用更新时触发RemoteServiceException崩溃
我之前也碰到过一模一样的问题——在Android 7.0及以上版本上传应用更新包时,突然抛出RemoteServiceException导致崩溃。仔细排查后发现,这几乎都是因为Android 7.0开始的后台Activity启动限制搞的鬼。
问题根源
Android 7.0(API 24)引入了后台操作权限收紧的机制,禁止应用在完全后台的状态下直接启动Activity。如果你的上传更新逻辑是在Service、子线程或者后台回调中触发了Activity启动(比如上传完成后弹出安装页面、结果提示页),系统就会拦截这个行为并抛出RemoteServiceException,也就是你看到的堆栈信息。
针对性解决方案
这里给你几个经过验证的解决办法,按优先级推荐:
优先推荐:用Notification引导用户主动触发Activity
既然后台不能直接启动页面,我们可以通过发送通知的方式,让用户点击通知来打开目标页面,这是符合系统规范的做法,兼容性最好。示例代码如下:// 初始化通知管理器 NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Android 8.0及以上需要创建通知渠道 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( "update_notify_channel", "应用更新通知", NotificationManager.IMPORTANCE_DEFAULT ); notificationManager.createNotificationChannel(channel); } // 构建跳转Activity的Intent Intent resultIntent = new Intent(this, UpdateResultActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE ); // 构建并发送通知 Notification notification = new NotificationCompat.Builder(this, "update_notify_channel") .setContentTitle("更新包上传完成") .setContentText("点击查看上传结果") .setSmallIcon(R.drawable.ic_app_update) .setContentIntent(pendingIntent) .setAutoCancel(true) .build(); notificationManager.notify(1001, notification);特殊场景备选:使用FLAG_ACTIVITY_NEW_TASK(仅兼容到Android 9)
如果你需要在旧版本(Android 7.0到9)下临时兼容,可以尝试给Intent添加FLAG_ACTIVITY_NEW_TASK标记,但注意Android 10及以上版本这个方法也会被限制,不推荐长期使用:Intent installIntent = new Intent(this, ApkInstallActivity.class); installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(installIntent);基础检查:确保UI操作在主线程执行
有时候上传逻辑在子线程中直接调用启动Activity的方法,也会触发异常。务必保证所有UI相关操作(包括启动Activity)都在主线程执行,可通过runOnUiThread实现:runOnUiThread(new Runnable() { @Override public void run() { // 在这里执行启动Activity的逻辑 } });
验证建议
你可以先定位到上传完成后的代码逻辑,看看是不是有后台启动Activity的操作,把这块替换成通知触发的方式,基本就能解决这个崩溃问题了。
内容的提问来源于stack exchange,提问作者Muhammad Ahmad

