Диспетчер работ не запускается при настройке приложения в api 27,28,29 - PullRequest
3 голосов
/ 09 июля 2020

У меня есть задача periodi c, которая запускается каждые 15 минут.

При настройке приложения. Не работает менеджер работы, если приложение убито из фона.

Тестовые устройства: One plus 7T, Nokia 5+, Google pixel 2 Emulator

Работа manager запускается только в том случае, если приложение находится либо на переднем плане, либо в фоновом режиме.

Отключение proguard Work Manager работает во всех трех условиях

  1. Приложение находится на переднем плане

  2. Приложение в фоновом режиме

  3. Приложение завершается из фона

Согласно поднятый мной вопрос https://issuetracker.google.com/issues/160492142#

Может быть проблема в файле proguard.

 #noinspection ShrinkerUnresolvedReference
 -keepattributes *Annotation*
 -keepattributes SourceFile,LineNumberTable
 # prevent Crashlytics obfuscation
 -keep class com.crashlytics.** { *; }
 -dontwarn com.crashlytics.**
 
 
 -keep public class * extends java.lang.Exception
 -keep class com.google.android.gms.measurement.AppMeasurement { *; }
 
 
 ###################################################################################################
 
 # Retrofit does reflection on generic parameters. InnerClasses is required to use Signature and
 # EnclosingMethod is required to use InnerClasses.
 -keepattributes Signature, InnerClasses, EnclosingMethod
 
 # Retrofit does reflection on method and parameter annotations.
 -keepattributes RuntimeVisibleAnnotations, RuntimeVisibleParameterAnnotations
 
 # Retain service method parameters when optimizing.
 -keepclassmembers,allowshrinking,allowobfuscation interface * {
     @retrofit2.http.* <methods>; }
 
 
 -keepclassmembers,allowobfuscation class * {   @com.squareup.moshi.Json <fields>; }
 # Ignore annotation used for build tooling.
 -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
 
 # Ignore JSR 305 annotations for embedding nullability information.
 -dontwarn javax.annotation.**
 
 # Guarded by a NoClassDefFoundError try/catch and only used when on the classpath.
 -dontwarn kotlin.Unit
 
 # Top-level functions that can only be used by Kotlin.
 -dontwarn retrofit2.KotlinExtensions
 -dontwarn retrofit2.KotlinExtensions$*
 
 # With R8 full mode, it sees no subtypes of Retrofit interfaces since they are created with a Proxy
 # and replaces all potential values with null. Explicitly keeping the interfaces prevents this.
 -if interface * { @retrofit2.http.* <methods>; }
 -keep,allowobfuscation interface <1>
 # Retrofit does reflection on method and parameter annotations.
 
 ###################################################################################################
 -keep class com.example.app.data.retrofit.**{ *; }
 
 ########################################OKHTTP#####################################################
 
 # JSR 305 annotations are for embedding nullability information.
 #-dontwarn javax.annotation.**
 
 # A resource is loaded with a relative path so the package of this class must be preserved.
 -keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
 
 # Animal Sniffer compileOnly dependency to ensure APIs are compatible with older versions of Java.
 -dontwarn org.codehaus.mojo.animal_sniffer.*
 
 # OkHttp platform used only on JVM and when Conscrypt dependency is available.
 -dontwarn okhttp3.internal.platform.ConscryptPlatform
 
 ###################################################################################################
 
 
 #-keepattributes Annotation
 #-keepattributes Signature,RuntimeVisibleAnnotations,AnnotationDefault
 #-keepattributes *Annotation*
 #-keepclassmembers enum androidx.lifecycle.Lifecycle.Event {
 #    <fields>;
 #}
 #-keep !interface * implements androidx.lifecycle.LifecycleObserver {
 #}
 #-keep class * implements androidx.lifecycle.GeneratedAdapter {
 #    <init>(...);
 #}
 
 ##noinspection ShrinkerUnresolvedReference
 #-keepclassmembers class android.arch.** { *; }
 #-keep class android.arch.** { *; }
 #-dontwarn android.arch.**
implementation "androidx.work:work-runtime:2.4.0-rc01"

Я перепробовал все версии. Но та же проблема. Он не работает на уровне API 27,28,29.

Диспетчер работ работает правильно на всех более старых уровнях API

Не означает это работает не работает только когда приложение убито .

Работает, когда приложение находится на переднем плане и когда приложение находится в фоновом режиме.

Диспетчер работ включен инициализировать вручную в классе приложения

 public void setWorker() {
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();
   
        PeriodicWorkRequest myWork =
                new PeriodicWorkRequest.
                        Builder(AppWorker.class,
                        15, TimeUnit.MINUTES, 5, TimeUnit.MINUTES)
                        .addTag("app_periodic")
                        .setConstraints(constraints)
                       .build();

            try {

            WorkManager.getInstance(MyApplication.this)
                    .enqueueUniquePeriodicWork("app_worker_notify", ExistingPeriodicWorkPolicy.KEEP, myWork);

        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

Пример кода

https://github.com/parmarravi/WorkManagerSample

обновление от 11-07-2020

Подробное исследование по этой проблеме.

Android Studio Work Manager Странное поведение

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...