WakefulBroadcastReceiver已被弃用。

29

为了创建一个接收器,我在我的旧项目中扩展了 WakefulBroadcastReceiver。但现在它已被deprecated。现在我应该使用哪个Receiver替代WakefulBroadcastReceiver,以及如何使用新方法转换下面的代码?

这是我的代码:

 public class TaskFinishReceiver extends WakefulBroadcastReceiver {
    private PowerManager mPowerManager;
    private PowerManager.WakeLock mWakeLock;
    @Override
    public void onReceive(Context context, Intent intent) {
        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        turnOnScreen();
        Intent wakeIntent = new Intent();

        wakeIntent.setClassName("com.packagename", "com.packagename.activity.TaskFinished");
        wakeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(wakeIntent);
    }


    public void turnOnScreen(){
        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
        mWakeLock.acquire();
    }
}
2个回答

15

您可以像这样重写您的代码:

    public class TaskFinishReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //do your stuff in the JobIntentService class
            MyJobIntentService.enqueueWork(context, intent);
        }
    }

根据文档所述,新的JobIntentService类将同时处理唤醒锁和向后兼容性,因此这将起作用:

使用此类时,不需要使用WakefulBroadcastReceiver。在 Android O 上运行时,JobScheduler 将为您处理唤醒锁(从您排队工作的时间开始保持唤醒锁,直到作业已被调度并在其运行时)。在早期的平台版本上运行时,该唤醒锁处理在此类中通过直接调用PowerManager来模拟实现;这意味着应用程序必须请求WAKE_LOCK权限。


2
这对我来说是一个更好的解决方案,因为我正在进行 Android O 的迁移,而我之前使用的 WakefulBroadcastReceiver->IntententService 模型可以很容易地转换为 BroadcastReceiver->JobIntentService! - Vinay
1
@Vinay JobIntentService现已弃用。 - AJW
1
JobIntentService已被弃用。请使用来自androidx的新JobIntentService。androidx.core.app.JobIntentService - jlguenego

7

WakefulBroadcastReceiver在API level 26.1.0已被废弃

从Android O开始,后台检查限制使得这个类不再一般适用。(因为你无法保证你的应用程序此时在前台运行并允许这样做,所以从广播接收到服务的启动通常是不安全的。)相反,开发人员应该使用android.app.job.JobScheduler来调度任务,这并不需要应用程序在此期间持有唤醒锁(系统将负责为该任务保持唤醒锁)。

public class JobSchedulerService extends JobService {

    @Override
    public boolean onStartJob(JobParameters params) {

        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {

        return false;
    }

}

针对演示案例,请查看


1
@Yeahia420 阅读文章 http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html - IntelliJ Amiya
4
如果您在这里提供有关作业调度程序的详细答案,将有助于其他人。 - Yeahia2508
JobService在Android O及其之前版本仍有限制。因此,请改用JobIntentService。更多详细信息请查看此处:https://medium.com/til-kotlin/jobintentservice-for-background-processing-on-android-o-39535460e060 - Chivorn
@Chivorn JobIntentService现已被弃用。 - AJW

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接