Android 9.0 NotificationManager.notify() 抛出 java.lang.SecurityException

标签 android notifications android-9.0-pie android-securityexception

我自己一直无法重现这个问题,但是到目前为止已经有 5 个用户报告了这个问题。我最近确实发布了一个应用程序更新,将目标 SDK 从 27 更改为 28,我肯定在其中发挥了作用。所有 5 个用户都在某种 Pixel 设备上运行某种风格的 Android 9。我也是。

应用程序通过调用设置通知和调用 NotificationManager.notify() 来响应警报情况。此通知引用尝试播放位于外部存储上的音频文件的通知 channel 。我的应用程序在 list 中包含 READ_EXTERNAL_STORAGE 权限。但由于它本身不访问外部存储中的任何内容,因此它没有要求用户授予它该权限。

当我在 Pixel 上执行此操作时,效果很好。但是有 5 位用户报告说它抛出了一个异常,比如

java.lang.RuntimeException: Unable to start activity ComponentInfo{net.anei.cadpage/net.anei.cadpage.CadPageActivity}: java.lang.SecurityException: UID 10132 does not have permission to content://media/external/audio/media/145 [user 0]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2914)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6680)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.SecurityException: UID 10132 does not have permission to content://media/external/audio/media/145 [user 0]
at android.os.Parcel.createException(Parcel.java:1950)
at android.os.Parcel.readException(Parcel.java:1918)
at android.os.Parcel.readException(Parcel.java:1868)
at android.app.INotificationManager$Stub$Proxy.enqueueNotificationWithTag(INotificationManager.java:1559)
at android.app.NotificationManager.notifyAsUser(NotificationManager.java:405)
at android.app.NotificationManager.notify(NotificationManager.java:370)
at android.app.NotificationManager.notify(NotificationManager.java:346)
at net.anei.cadpage.ManageNotification.show(ManageNotification.java:186)
at net.anei.cadpage.ReminderReceiver.scheduleNotification(ReminderReceiver.java:46)
at net.anei.cadpage.ManageNotification.show(ManageNotification.java:161)
at net.anei.cadpage.CadPageActivity.startup(CadPageActivity.java:211)
at net.anei.cadpage.CadPageActivity.onCreate(CadPageActivity.java:93)
at android.app.Activity.performCreate(Activity.java:7144)
at android.app.Activity.performCreate(Activity.java:7135)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2894)
... 11 more
Caused by: android.os.RemoteException: Remote stack trace:
at com.android.server.am.ActivityManagerService.checkGrantUriPermissionLocked(ActivityManagerService.java:9752)
at com.android.server.am.ActivityManagerService.checkGrantUriPermission(ActivityManagerService.java:9769)
at com.android.server.notification.NotificationRecord.visitGrantableUri(NotificationRecord.java:1096)
at com.android.server.notification.NotificationRecord.calculateGrantableUris(NotificationRecord.java:1072)
at com.android.server.notification.NotificationRecord.<init>(NotificationRecord.java:201)

我已经告诉所有 4 个用户手动授予“存储”权限,AFAIK 解决了这个问题。但为什么这是必要的。我没有访问外部存储本身,也没有设置 channel 配置来要求它。如果需要 READ_EXTERNAL_STORAGE 权限,则应由通知管理器进行管理。

用户报告问题正在运行以下: 谷歌/taimen/taimen:9/PQ1A.190105.004/5148680:user/release-keys 谷歌/crosshatch/crosshatch:9/PQ1A.190105.004/5148680:user/release-keys 谷歌/马林鱼/马林鱼:9/PQ1A.181205.002.A1/5129870:user/release-keys 谷歌/旗鱼/旗鱼:9/PQ1A.181205.002.A1/5129870:user/release-keys google/walleye/walleye:9/PQ1A.181205.002/5086253:user/release-keys

我在运行 谷歌/taimen/taimen:9/PQ1A.181205.002/5086253:user/release-keys 似乎落后于其他所有人,更新为 谷歌/taimen/taimen:9/PQ1A.190105.004/5148680:user/release-keys 没有改变任何东西。在我的设备上仍然可以正常工作。

以下是所有代码,其中包含一些关于采用哪些分支的提示。堆栈跟踪非常清楚异常是在 notify() 调用中抛出的。并且中止被抛出是因为该应用没有对 channel 指定的音频文件的安全访问权限。

// Build and launch the notification
Notification n = buildNotification(context, message);

NotificationManager myNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert myNM != null;

// Seems this is needed for the number value to take effect on the Notification
activeNotice = true;
myNM.cancel(NOTIFICATION_ALERT);
myNM.notify(NOTIFICATION_ALERT, n);

........

private static Notification buildNotification(Context context, SmsMmsMessage message) {

/*
 * Ok, let's create our Notification object and set up all its parameters.
 */
NotificationCompat.Builder nbuild = new NotificationCompat.Builder(context, ALERT_CHANNEL_ID);

// Set auto-cancel flag
nbuild.setAutoCancel(true);

// Set display icon
nbuild.setSmallIcon(R.drawable.ic_stat_notify);

// From Oreo on, these are set at the notification channel level
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {  // False

  // Maximum priority
  nbuild.setPriority(NotificationCompat.PRIORITY_MAX);

  // Message category
  nbuild.setCategory(NotificationCompat.CATEGORY_CALL);

  // Set public visibility
  nbuild.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

  // Set up LED pattern and color
  if (ManagePreferences.flashLED()) {
    /*
     * Set up LED blinking pattern
     */
    int col = getLEDColor(context);
    int[] led_pattern = getLEDPattern(context);
    nbuild.setLights(col, led_pattern[0], led_pattern[1]);
  }

  /*
   * Set up vibrate pattern
   */
  // If vibrate is ON, or if phone is set to vibrate
  AudioManager AM = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
  assert AM != null;
  if ((ManagePreferences.vibrate() || AudioManager.RINGER_MODE_VIBRATE == AM.getRingerMode())) {
    long[] vibrate_pattern = getVibratePattern(context);
    if (vibrate_pattern != null) {
      nbuild.setVibrate(vibrate_pattern);
    } else {
      nbuild.setDefaults(Notification.DEFAULT_VIBRATE);
    }
  }
}

if ( ManagePreferences.notifyEnabled()) {  // false

  // Are we doing are own alert sound?
  if (ManagePreferences.notifyOverride()) {

    // Save previous volume and set volume to max
    overrideVolumeControl(context);

    // Start Media Player
    startMediaPlayer(context, 0);
  } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
    Uri alarmSoundURI = Uri.parse(ManagePreferences.notifySound());
    nbuild.setSound(alarmSoundURI);
  }
}

String call = message.getTitle();
nbuild.setContentTitle(context.getString(R.string.cadpage_alert));
nbuild.setContentText(call);
nbuild.setStyle(new NotificationCompat.InboxStyle().addLine(call).addLine(message.getAddress()));
nbuild.setWhen(message.getIncidentDate().getTime());

// The default intent when the notification is clicked (Inbox)
Intent smsIntent = CadPageActivity.getLaunchIntent(context, true);
PendingIntent notifIntent = PendingIntent.getActivity(context, 0, smsIntent, 0);
nbuild.setContentIntent(notifIntent);

// Set intent to execute if the "clear all" notifications button is pressed -
// basically stop any future reminders.
Intent deleteIntent = new Intent(new Intent(context, ReminderReceiver.class));
deleteIntent.setAction(Intent.ACTION_DELETE);
PendingIntent pendingDeleteIntent = PendingIntent.getBroadcast(context, 0, deleteIntent, 0);
nbuild.setDeleteIntent(pendingDeleteIntent);

return nbuild.build();
}

最新消息。昨晚我发布了一个更新,支持目标 SDK 从 28 回到 27。一夜之间,又有 2 名用户报告了运行 Android 9 的 Pixel 手机上的这一特殊崩溃。两者都运行了针对 SDK 28 的版本。有人回复我并确认了这个问题当他们安装 SDK 27 版本的应用程序时消失了。这证实这是针对 SDK 28 的应用程序的一个问题,可能与不允许应用程序使用世界访问文件系统权限以打破应用程序沙箱限制的更改有关。

为什么它会影响某些用户而不影响其他用户,这仍然是一个谜。特别是我。当我有时间时,我将再次尝试在我的手机上重现该问题。两种理论是 1)它只会攻击从未授予 READ_EXTERNAL_STORAGE 权限的人。我的最初获得了该许可,但在尝试重现该问题时我撤销了该许可。 2) 仅当使用外部音频文件的通知 channel 最初由应用程序设置时才会发生。对于大多数用户来说都是如此,但就我而言,声音文件是手动设置的。

最佳答案

与其说是一个解决方案,不如说是一个漫长而复杂的解决方法。

首先,我捕获了通知抛出的 SecurityException 并设置了共享首选项标志

try {
  myNM.notify(NOTIFICATION_ALERT, n);
} catch (SecurityException ex) {
  Log.e(ex);
  ManagePreferences.setNotifyAbort(true);
  return;
}

当应用程序启动时,它会检查此标志并设置它,提示用户授予 READ_EXTERNAL_PERMISSION。不包括代码,因为它是一个复杂系统的一部分,该系统将权限与不同的首选项设置相关联,仅在授予所需权限时才允许某些设置,如果未授予权限则更改它。

这有帮助,但我们仍然意味着用户不会在第一次需要生成警报时得到通知。为了解决这个问题,我们在启动初始化中添加了一些东西来检查是否有问题,如果有,生成一个定期通知并立即取消它。

if (audioAlert && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
  if (! ManagePreferences.notifyCheckAbort() &&
      ! PermissionManager.isGranted(context, PermissionManager.READ_EXTERNAL_STORAGE)) {
    Log.v("Checking Notification Security");
    ManagePreferences.setNotifyCheckAbort(true);
    ManageNotification.show(context, null, false, false);
    NotificationManager myNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    assert myNM != null;
    myNM.cancel(NOTIFICATION_ALERT);
  }
}

越来越近了。但如果它发生在用户升级到 Android 9 之后但在他们打开应用程序之前,我们仍然会错过警报通知。为了解决这个问题,我写了一个广播接收器来监听 android.intent.action.MY_PACKAGE_REPLACED 和 android.intent.action.BOOT_COMPLETED 每次升级我的应用程序或升级 Android 系统时都会调用它。这个接收器没有做任何特别的事情。但它存在的事实意味着我的应用程序启动并通过初始化逻辑。它检测到用户需要 READ_EXTERNAL_STORAGE 权限并提示他们。

关于Android 9.0 NotificationManager.notify() 抛出 java.lang.SecurityException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54120745/

相关文章:

java - Android -- 蓝牙读写问题?

android - javax.net.ssl.SSLException:读取错误:ssl = 0x9524b800:系统调用期间发生I/O错误,对等方重置了连接

android - 带有 setGroupSummary(true) 的通知在 Android N 中不可见

Android 9 ResolvableApiException onActivityResult 有 resultCode 0 RESULT_CANCELED

android - Android P 中不推荐使用的 fragment

android - 选择大于 3mb 的照片时,cordova 应用程序崩溃

android - 构建 Apk 错误 - 重复条目 : android/support/v4/database/DatabaseUtilsCompat. 类?

android - 如何在android中通知需要WAKE_LOCK?

sql-server - 存储过程执行时间过长时发出 SQL 警报

android - DialogFragment 将 EditText 聚焦在为 API 28 打开的对话框上