La orientación a S+ (versión 31 y superior) requiere que se especifique uno de FLAG_IMMUTABLE o FLAG_MUTABLE

5 minutos de lectura

Avatar de usuario de Mouaad Abdelghafour AITALI
Mouaad Abdelghafour AITALI

La aplicación falla en tiempo de ejecución con el siguiente error:

java.lang.IllegalArgumentException: maa.abc: la orientación a S+ (versión 31 y superior) requiere que se especifique FLAG_IMMUTABLE o FLAG_MUTABLE al crear un PendingIntent. Considere seriamente usar FLAG_IMMUTABLE, solo use FLAG_MUTABLE si alguna funcionalidad depende de que el PendingIntent sea mutable, por ejemplo, si necesita usarse con respuestas en línea o burbujas. en android.app.PendingIntent.checkFlags(PendingIntent.java:375) en android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:645) en android.app.PendingIntent.getBroadcast(PendingIntent.java:632) en com.google. android.exoplayer2.ui.PlayerNotificationManager.createBroadcastIntent(PlayerNotificationManager.java:1373) en com.google.android.exoplayer2.ui.PlayerNotificationManager.createPlaybackActions(PlayerNotificationManager.java:1329) en com.google.android.exoplayer2.ui.PlayerNotificationManager. (PlayerNotificationManager.java:643) en com.google.android.exoplayer2.ui.PlayerNotificationManager.(PlayerNotificationManager.java:529) en com.google.android.exoplayer2.ui.PlayerNotificationManager.createWithNotificationChannel(PlayerNotificationManager.java:456) en com .google.android.exoplayer2.ui.PlayerNotificationManager.createWithNotificationChannel(PlayerNotificationManager.java:417)

Probé todas las soluciones disponibles, pero la aplicación sigue fallando en Android 12.

 @Nullable
 @Override
 public PendingIntent createCurrentContentIntent(@NonNull Player player) {
        Intent intent = new Intent(service, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_SINGLE_TOP |
                        Intent.FLAG_ACTIVITY_NEW_TASK);
        return PendingIntent.getActivity(service, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

 }

Si usa java o react-native, pegue esto dentro de app/build.gradle

dependencies {
  // ...
  implementation 'androidx.work:work-runtime:2.7.1'
}

Si usa Kotlin, use esto

dependencies {
  // ...
  implementation 'androidx.work:work-runtime-ktx:2.7.0'
}

y si alguien todavía enfrenta el problema de bloqueo para Android 12, asegúrese de agregar lo siguiente en AndroidMenifest.xml

 <activity 
   ...
   android:exported="true" // in most cases it is true but based on requirements it can be false also   
>   


   // If using react-native push notifications then make sure to add into it also

 <receiver   
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver" android:exported="true">
 
   //  Similarly
 
 <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService" android:exported="true">

  • Incluso después de agregar FLAG_IMMUTABLE y la dependencia, sigo recibiendo el error en algunos dispositivos Samsung: Galaxy Note20 5G, Galaxy S20 FE 5G y otros.

    – John Doe

    6 de mayo a las 12:27


  • Sí, también lo encontré en dispositivos Samsung y HTC. Publicaré soluciones una vez que lo resuelva.

    – Haryanvi Desarrollador

    7 de mayo a las 18:05

  • Por favor, echa un vistazo a este comentario. github.com/facebook/react-native/issues/…

    – Hamza Hmem

    19 de mayo a las 16:24

  • Gracias @HamzaHmem, ¿te funciona esto? ¿has probado?

    – Haryanvi Desarrollador

    27 de mayo a las 12:41

  • @HaryanviDeveloper Probé tu solución y funcionó. Sin embargo, hay una solución desarrollada por el propio equipo nativo de reacción, pero se lanzará con la versión 0.69.

    – Hamza Hmem

    29 de mayo a las 9:46

Avatar de usuario de Saksham Pruthi
Saksham Pruti

Verifique y actualice la versión de dependencia de exoplayer a la última

android.app.PendingIntent.getBroadcast() anteriormente utilizado para volver

@Nullable
@Override
private static PendingIntent createBroadcastIntent(
    String action, Context context, int instanceId) {
    Intent intent = new Intent(action).setPackage(context.getPackageName());
    intent.putExtra(EXTRA_INSTANCE_ID, instanceId);
    return PendingIntent.getBroadcast(
        context, instanceId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  }

Si observa cuidadosamente, falta PendingIntent.FLAG_IMMUTABLE aquí en el fragmento anterior

Ahora se ha actualizado para devolver lo siguiente

@Nullable
@Override
private static PendingIntent createBroadcastIntent(
      String action, Context context, int instanceId) {
    Intent intent = new Intent(action).setPackage(context.getPackageName());
    intent.putExtra(EXTRA_INSTANCE_ID, instanceId);

    int pendingFlags;
    if (Util.SDK_INT >= 23) {
      pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
    } else {
      pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT;
    }

    return PendingIntent.getBroadcast(context, instanceId, intent, pendingFlags);
  }

  • Genial, pero ¿por qué deberíamos verificar la versión 23 y superior cuando el mensaje de error es “Targeting S+ (versión 31 y superior)”

    – Tarek

    8 de febrero a las 6:49

  • @Tarek PendingIntent.FLAG_IMMUTABLE no está presente en API por debajo de 23. El mensaje de error se debe a que Android ha hecho obligatorio agregar PendingIntent.FLAG_IMMUTABLE o PendingIntent.FLAG_IMUTABLE a todos los intentos pendientes desde API 31(S) en adelante

    – Saksham Pruti

    8 de febrero a las 14:15

  • Observó que el uso de la Util.SDK_INT Es posible que las constantes no sean muy portátiles para la mayoría de los proyectos, por lo que recomendaría el uso de Android “oficial” Build.VERSION.SDK_INT variantes.

    – JWL

    5 de julio a las 8:30

Solución para Kotlin, solo agregue esta bandera si está con API M

val flags = when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE
            else -> FLAG_UPDATE_CURRENT
        }
val toastPendingIntent = PendingIntent.getBroadcast(context, 0, providerIntent, flags)

En mi caso, para leer etiquetas usando el sistema de entrega en primer plano, funciona…

Si permite que su aplicación se ejecute en Android 12, use lo siguiente:

PendingIntent pendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
   pendingIntent = PendingIntent.getActivity(this,
          0, new Intent(this, getClass()).addFlags(
   Intent.FLAG_ACTIVITY_SINGLE_TOP), 
   PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
}else {
   pendingIntent = PendingIntent.getActivity(this,
      0, new Intent(this, getClass()).addFlags(
   Intent.FLAG_ACTIVITY_SINGLE_TOP), 
   PendingIntent.FLAG_UPDATE_CURRENT);
}

Enfrento el mismo problema y, como se indica en la mayoría de las respuestas, actualicé mi dependencia de la siguiente manera.

dependencies {
  /* Use either Kotlin or Java dependency as per your project */

  // ...
  /* Android Arch Component Work Manager for Kotlin */
  implementation 'androidx.work:work-runtime-ktx:2.7.0' 


  //...
  /* Android Arch Component Work Manager for Java */
  def work_version = "2.7.1"
  implementation "androidx.work:work-runtime:$work_version"
  // optional - Test helpers
  androidTestImplementation "androidx.work:work-testing:$work_version"
}

Pero agregar solo lo anterior no resolvió mi problema y la aplicación aún se bloqueó.

Así que apagué Android Lint: Missing Pending Intent Mutability, encuentre los pasos a continuación para apagar.

Desactivar la mutabilidad de intención pendiente

Vaya a la opción Buscar y busque “PendingIntent” y recibirá una ventana como la que se muestra a continuación.

Ventana de búsqueda de Android Studio

Cambie de Android Lint: falta la mutabilidad de intención pendiente y está listo para comenzar.

Avatar de usuario de Ajay
Ajay

Resolví esto agregando a continuación en …android/app/build.gradle

implementation 'androidx.work:work-runtime-ktx:2.8.0-alpha01'

https://github.com/react-native-maps/react-native-maps/issues/4083#issue-1119280606

Si el Arrojar biblioteca produce su problema, no podrá usarla después de actualizar la versión SDK. Puedes reemplazarlo fácilmente con tirador (el tenedor de Chuck): https://github.com/jgilfelt/chuck/issues/101#issuecomment-869119599.

¿Ha sido útil esta solución?