web-dev-qa-db-fra.com

Android Notification en plein écran ne figurera pas sur l'écran de verrouillage

J'essaie de créer un Android Notification en plein écran pour afficher une activité sur l'écran de verrouillage, comme une réveil.

La notification survient toujours, mais l'activité n'est jamais démarrée sur l'écran de verrouillage; Il sonne et montre une icône de notification sur l'écran de verrouillage si le téléphone est éteint. Il montre une notification heads up si le téléphone est allumé comme prévu. Une impression de débogage indique que le canal de notification est enregistré avec succès au niveau de l'importance haut/4 comme demandé.

Je l'ai essayé sur 5 différent Android Versions de périphérique: Android 10, 8.0.0, 6.0.1, 5.1.1.1.1

J'ai suivi le Android Documentation Documentation liée ci-dessous. Je suis également liée à quelques questions de dépassement de pile similaires.

https://developer.andrid.com/training/notify-user/time-senitive

https://developer.andrid.com/training/notify-user/build-notification#urgent-message

Intention en plein écran ne démarre pas l'activité mais affiche une notification sur Android 1

Notification en plein écran

Vous trouverez ci-dessous une version très minimale du code d'application, une activité avec 1 bouton pour planifier la notification à l'avenir avec un récepteur de diffusion afin qu'il tire une fois que l'écran est verrouillé.

    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    minSdkVersion 25
    targetSdkVersion 29

    <uses-permission Android:name="Android.permission.DISABLE_KEYGUARD" />
    <uses-permission Android:name="Android.permission.USE_FULL_SCREEN_INTENT" />

public class AppReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (FullscreenActivity.FULL_SCREEN_ACTION.equals(intent.getAction()))
            FullscreenActivity.CreateFullScreenNotification(context);
    }
}

public class FullscreenActivity extends AppCompatActivity {

    private static final String CHANNEL_ID = "my_channel";
    static final String FULL_SCREEN_ACTION = "FullScreenAction";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fullscreen);
        createNotificationChannel(this);
    }

    /**
     * Use button to set alarm manager with a pending intent to create the full screen notification
     * after use has time to shut off device to test with the lock screen showing
     */
    public void buttonClick(View view) {
        Intent intent = new Intent(this, AppReceiver.class);
        intent.setAction(FULL_SCREEN_ACTION);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        if (am != null) {
            am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 15000, pi);
        }
    }

    static void CreateFullScreenNotification(Context context) {
        Intent fullScreenIntent = new Intent(context, FullscreenActivity.class);
        fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);//?
        PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(context, 0,
                fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(context, CHANNEL_ID)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentTitle("Full Screen Alarm Test")
                        .setContentText("This is a test")
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setCategory(NotificationCompat.CATEGORY_CALL)
                        .setDefaults(NotificationCompat.DEFAULT_ALL) //?
                        .setFullScreenIntent(fullScreenPendingIntent, true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        notificationManager.notify(1, notificationBuilder.build());
    }

    private static void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);

            if (notificationManager != null && notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);
                channel.setDescription("channel_description");
                notificationManager.createNotificationChannel(channel);
            }

            //DEBUG print registered channel importance
            if (notificationManager != null && notificationManager.getNotificationChannel(CHANNEL_ID) != null) {
                Log.d("FullScreenActivity", "notification channel importance is " + notificationManager.getNotificationChannel(CHANNEL_ID).getImportance());
            }
        }
    }
}
4
Robb Peebles

J'étais enfin capable de faire fonctionner cela après avoir trouvé cette réponse pour un appel entrant: https://stackoverflow.com/a/53192049/13008865

La partie manquante du Android Exemples de document pour des intentions d'écran complet était que l'activité L'intention de l'écran entier tente de montrer les besoins en a besoin d'un couple WindowManager.LayOntParams drapeaux Set: flag_show_when_locked et flag_turn_screen_on.

Voici le code de test minimal final, j'espère que l'espoir est utile pour d'autres essayant d'effectuer une application de type de réveil. J'ai testé avec succès sur les versions 4 OS énumérées ci-dessus avec la cible SDK 29 et le minimum SDK 15. La seule autorisation manifeste requise était utilisée_full_screen_intent et uniquement pour les périphériques exécutés Android Q/29 et ci-dessus.

public class AppReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (FullscreenActivity.FULL_SCREEN_ACTION.equals(intent.getAction()))
            FullscreenActivity.CreateFullScreenNotification(context);
    }
}

public class FullscreenActivity extends AppCompatActivity {

    private static final String CHANNEL_ID = "my_channel";
    static final String FULL_SCREEN_ACTION = "full_screen_action";
    static final int NOTIFICATION_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fullscreen);
        createNotificationChannel(this);

        //set flags so activity is showed when phone is off (on lock screen)
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    /**
     * Use button to set alarm manager with a pending intent to create the full screen notification
     * after use has time to shut off device to test with the lock screen showing
     */
    public void buttonClick(View view) {
        Intent intent = new Intent(FULL_SCREEN_ACTION, null, this, AppReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 15000, pendingIntent);
        }

        NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID); //cancel last notification for repeated tests
    }

    static void CreateFullScreenNotification(Context context) {
        Intent intent = new Intent(context, FullscreenActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(context, CHANNEL_ID)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentTitle("Full Screen Alarm Test")
                        .setContentText("This is a test")
                        .setPriority(NotificationCompat.PRIORITY_MAX)
                        .setCategory(NotificationCompat.CATEGORY_ALARM)
                        .setContentIntent(pendingIntent)
                        .setFullScreenIntent(pendingIntent, true);
        NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notificationBuilder.build());
    }

    private static void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

            if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);
                channel.setDescription("channel_description");
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
}
5
Robb Peebles