不推荐使用WakefulBroadcastReceiver [英] WakefulBroadcastReceiver is deprecated

查看:431
本文介绍了不推荐使用WakefulBroadcastReceiver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For creating a receiver I'm extended WakefulBroadcastReceiver in my old project. But now it's deprecated. Instead of WakefulBroadcastReceiver which Receiver I should use now and how to convert below code with new method?

这是我的代码:

 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();
    }
}


推荐答案

您可以这样重写代码:

    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 类将处理唤醒锁和向后兼容性:

This will work since, according to documentation, the new JobIntentService class will handle both wake locks and backward compatibility:


使用此类时,无需使用WakefulBroadcastReceiver。在Android O上运行时,JobScheduler将为您处理唤醒锁(从将工作入队到作业被分派以及运行时一直保持唤醒锁)。在平台的早期版本上运行时,此唤醒锁处理在此处的类中通过直接调用PowerManager进行模拟。这意味着应用程序必须请求WAKE_LOCK权限。

You do not need to use WakefulBroadcastReceiver when using this class. When running on Android O, the JobScheduler will take care of wake locks for you (holding a wake lock from the time you enqueue work until the job has been dispatched and while it is running). When running on previous versions of the platform, this wake lock handling is emulated in the class here by directly calling the PowerManager; this means the application must request the WAKE_LOCK permission.

这篇关于不推荐使用WakefulBroadcastReceiver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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