在API 27、28、29中保护应用程序时,工作管理器无法运行 [英] Work manager do not run when proguarding app in api 27,28,29

查看:85
本文介绍了在API 27、28、29中保护应用程序时,工作管理器无法运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定期任务,每15分钟运行一次.

I have a periodic task that runs every 15 minutes.

保护应用程序时.如果该应用被后台杀死,则工作管理器将无法工作.

When proguarding the application. The work manager does not work if the app is killed from the background.

测试设备:一加7T,诺基亚5+,谷歌Pixel 2仿真器

Testing devices : One plus 7T, Nokia 5+ ,Google pixel 2 Emulator

仅当应用程序在前台或后台时,工作管理器才会执行.

The work manager only gets executed if app is either in the foreground or is in the background.

禁用proguard Work Manager可以在所有3种情况下工作

Disabling the proguard Work manager works in all 3 condition

  1. 该应用位于前台

  1. The app is in foreground

后台运行的应用程序

该应用被从后台杀死

根据我在> https://issuetracker.google.com/issues/160492142#

proguard文件中可能有问题.

There might be issue in proguard file.

 #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中不起作用.

I have tried all the versions. But the same issue is there. It doesn't work in Api Level 27,28,29.

工作管理器可以在所有较旧的API级别正常工作

Work manager work correctly in all the older API level's

并不意味着,它仅在应用被杀死时才不起作用.

当应用程序在前台时,当应用程序在后台时,它可以工作.

It works when app is in the foreground and when app is in the background.

工作管理器已在应用程序类中手动初始化

Work manager is been initialize manually in application class

 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

自2020年11月7日起更新

有关此问题的详细研究.

A detailed study on this issue.

Android Studio工作管理器的异常行为

推荐答案

发生这种情况的原因是今天各家供应商对电池进行了优化.您需要禁用优化功能,您的工作经理将像超级英雄一样工作!!

This happened due to battery optimization by various vendors this day. You need to disable the optimization and your work manager will work like a charm!!

 private void checkBatteryOptimization(){

        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName())) {
                AlertBottomSheetFragment alertBottomSheetFragment = AlertBottomSheetFragment.newInstance();
                alertBottomSheetFragment.setData("For Timely notifications please disable battery optimization for Your App", new AlertBottomSheetImpl() {
                    @Override
                    public void acceptAlertBottom() {
                        askIgnoreOptimization();
                    }

                    @Override
                    public void declineAlertBottom() {

                    }
                });
                alertBottomSheetFragment.show(getSupportFragmentManager(), FRAG_BOTTOM_SHEET_ALERT_TAG);

            } else {
                // already ignoring battery optimization code here next you want to do
                Timber.i("already ignoring battery optimization code here next you want to do");
            }
        } else {
            Timber.i("version below");
            // already ignoring battery optimization code here next you want to do
        }
    }

    private void askIgnoreOptimization() {

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, IGNORE_BATTERY_OPTIMIZATION_REQUEST);
        }
    }

这篇关于在API 27、28、29中保护应用程序时,工作管理器无法运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆