1
votes

Workmanager ne fonctionne pas lorsque l'application est en arrière-plan

J'essaie d'exécuter périodiquement un service même lorsque l'application est tuée ou est en arrière-plan à l'aide de workManager.

Ma classe RequestService est donnée ci-dessous: -

        final PeriodicWorkRequest WorkReq = new PeriodicWorkRequest.Builder(RequestService.class,15,TimeUnit.MINUTES).build();
        WorkManager.getInstance().enqueue(WorkReq);

Voici le code de l'activité principale: -

public class RequestService extends Worker {

public RequestService(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {

    displayNotification("MY Worker", "Background work Started");
    Log.i("BackJob","Running");
    return Result.SUCCESS;
}

private void displayNotification(String title, String task){

    NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel("MyApp","My Notifications",
                                                    NotificationManager.IMPORTANCE_HIGH);

        notificationManager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), "My Notifications").
                                                    setContentTitle(title).setContentText(task)
                                                            .setSmallIcon(R.mipmap.ic_launcher);

    notificationManager.notify(130, notification.build());

}}

Le problème est que si l'application est tuée ou est en arrière-plan, alors Workmanager cesse de fonctionner. Je teste ceci sur un appareil Samsung avec la tarte de la version Android.

PS: - si l'application est ouverte, je vois des notifications en continu après 15 minutes ... mais dès que je ferme l'application. .... ça cesse de fonctionner ..... et il n'y a plus de notifications


2 commentaires

Pouvez-vous jeter un œil à la source du laboratoire de codes WorkManager? il implémente certaines classes Worker affichant une notification. Il inclut une makeStatusNotification qui résout le même problème: github.com/googlecodelabs/android-workmanager/blob/...


Avez-vous la solution? Je suis confronté à un problème similaire.


3 Réponses :


1
votes

Selon la documentation officielle PeriodicWorkRequest.Builder disponible ici < / p>

L'intervalleMillis doit être supérieur ou égal à PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS

Cette valeur est actuellement fixée à 900 000 ms, soit 15 minutes.


3 commentaires

Reportez-vous au message .... c'est ce que j'utilise .... 15 minutes, TimeUnit.MINUTES


Ok, avez-vous testé sur d'autres appareils. Les appareils Samsung ont des problèmes de test.


Oui, toujours pas de succès



0
votes

Ceci est un exemple fonctionnel qui affiche actuellement toute notification concernant la version du SO. Mais apparemment, le problème peut être lié à la méthode notify de NotificationManagerCompat

private void makeStatusNotification(String message, Context context) {

    String channelId = context.getString(R.string.worker_sync_notif_channel_id);

    // Make a channel if necessary
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // Create the NotificationChannel, but only on API 26+
        CharSequence name = context.getString(R.string.worker_sync_notif_channel_name);
        String description = context.getString(R.string.worker_sync_notif_channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel(channelId, name, importance);
        channel.setDescription(description);
        // Add the channel
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }

    // Create the notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_cloud_upload)
            .setContentTitle(context.getString(R.string.worker_sync_notif_title))
            .setContentText(context.getString(R.string.worker_sync_notif_subject))
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(message))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setVibrate(new long[0])
            .setAutoCancel(true);

    // Show the notification
    NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build());
}


1 commentaires

Désolé pour la réponse tardive ..... merci pour les ans .... et je suis capable d'afficher les notifications, mais quand l'application est en arrière-plan, le gestionnaire arrête les demandes périodiques



2
votes

Vous pouvez utiliser le service de premier plan pour cela, le service de premier plan fonctionne lorsque l'application est en arrière-plan.

ajoutez cette méthode dans la méthode downork

 @NonNull
    private ForegroundInfo createForegroundInfo(@NonNull String progress) {

        Context context = getApplicationContext();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan = new NotificationChannel("1", "channelName", NotificationManager.IMPORTANCE_NONE);
            chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            assert manager != null;
            manager.createNotificationChannel(chan);
        }

        Notification notification = new NotificationCompat.Builder(context, "1")
                .setContentTitle("title")
                .setTicker("title")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setOngoing(true)
                .build();

        return new ForegroundInfo(1,notification);
    }

Remplacez cette méthode dans workermanager class

setForegroundAsync(createForegroundInfo(progress));

Maintenant, votre application fonctionnera en arrière-plan.


1 commentaires

Quelqu'un a essayé cette solution? - Surtout sur Android 9 et 10? -