【问题标题】:Android 12 Pending IntentAndroid 12 待定意向
【发布时间】:2022-04-07 17:10:36
【问题描述】:

定位 S+(版本 31 及更高版本)要求在创建 PendingIntent 时指定 FLAG_IMMUTABLE 或 FLAG_MUTABLE 之一。强烈考虑使用 FLAG_IMMUTABLE,仅当某些功能依赖于 PendingIntent 可变时才使用 FLAG_MUTABLE

我无法在 android studio 项目编码中更新待定意图标志

这是AlarmPingSender.java中发生错误的地方

  public void start()        
   {       
   String action = MqttServiceConstants.PING_SENDER
            + comms.getClient().getClientId();
    Log.d(TAG, "Register alarmreceiver to MqttService"+ action);
    service.registerReceiver(alarmReceiver, new IntentFilter(action));

    pendingIntent = PendingIntent.getBroadcast(service, 0, new Intent(
            action), PendingIntent.FLAG_UPDATE_CURRENT);

    schedule(comms.getKeepAlive());
    hasStarted = true;
}

帮我解决问题 ERROR IN ANDROID STUDIO IMAGE

【问题讨论】:

  • 欢迎来到 Stackoverflow!请编辑您的问题并添加创建 PendingIntent 的代码。
  • 请大家帮忙
  • 错误信息告诉你应该做什么。 Stackoverflow 上也有很多问题涵盖了这个确切的问题。见developer.android.com/guide/components/…
  • 我不知道在哪里更改代码的待定意图,我们尝试了很多方法和代码中的各个位置,但它不起作用

标签: android android-studio android-pendingintent


【解决方案1】:

当您想在项目中创建任何PendingIntent 时,请使用这两个公共方法

创建活动pendingIntent

   public static PendingIntent createPendingIntentGetActivity(Context context, int id, Intent intent, int flag) {
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
             return PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_IMMUTABLE | flag);
         } else {
             return PendingIntent.getActivity(context, id, intent, flag);
         }
     }

创建广播pendingIntent

 public static PendingIntent createPendingIntentGetBroadCast(Context context, int id, Intent intent, int flag) {
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
         return PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_IMMUTABLE | flag);
     } else {
         return PendingIntent.getBroadcast(context, id, intent, flag);
     }
 }

【讨论】:

    【解决方案2】:

    你需要这样做:

    pendingIntent = PendingIntent.getBroadcast(service, 0, new Intent(
            action), PendingIntent.FLAG_UPDATE_CURRENT |
                     PendingIntent.FLAG_IMMUTABLE);
    

    由于您使用的是AlarmManager,您应该能够使用IMMUTABLE 标志。

    【讨论】:

    • 先生,我能知道我们需要使用此代码的确切位置吗,因为我们已经尝试过,它对我们不起作用。我们在 AlarmPingIntent 工作来改变这一点
    • 你见过这个吗?您使用的是同一个 MQTT 库吗? stackoverflow.com/questions/71155187/…
    • 该票证中有指向该库的另一个版本的链接,可以解决您的问题。
    • 您能否通过链接解决方案解决您的问题?
    • @AJW 一般来说,如果您将PendingIntent 提供给另一个应用程序,并且该应用程序需要在最终触发PendingIntent 时添加/修改Intent,则需要使用FLAG_MUTABLE
    猜你喜欢
    • 2021-12-18
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多