其他分享
首页 > 其他分享> > android-使用JobScheduler代替BroadcastReceiver和Service

android-使用JobScheduler代替BroadcastReceiver和Service

作者:互联网

我正在开发一个应用程序,当设备连接到互联网时,该应用程序将在后台将所有数据库记录顺序上传到服务器.

为此,我编写了一个BroadcastReceiver,它将监听网络连接.触发此接收器后,我将启动后台服务以上传记录.

这是我的代码.

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
       AppUtils.checkInternetConnection(context));
        //If the device has the internet connection and if there are any pending records to upload to server then start the service for uploading the records.
        if (AppUtils.checkInternetConnection(context)) {
            if (Database.getInstance().getTotalRecordsCount() > 0) {
                context.startService(new Intent(context, SurveyUploadService.class));
            }
        } else {
            context.stopService(new Intent(context, SurveyUploadService.class));
        }
    }
}

现在我的疑问是

1.我可以使用JobScheduler做同样的事情吗?
 2.有什么更好的方法(我的还是使用JobScheduler的方法)?为什么?

解决方法:

我不知道您要对BroadcastReceiver使用哪个操作,但是我想它是CONNECTIVITY_CHANGE操作.如果使用它,请从大约Android 7.0 Behavior Changes的一侧阅读以下文本:

To alleviate these issues, Android 7.0 applies the following optimizations:

  • Apps targeting Android 7.0 do not receive CONNECTIVITY_ACTION broadcasts, even if they have manifest entries to request notification of these events. Apps that are running can still listen for CONNECTIVITY_CHANGE on their main thread if they request notification with a BroadcastReceiver.

  • Apps cannot send or receive ACTION_NEW_PICTURE or ACTION_NEW_VIDEO broadcasts. This optimization affects all apps, not only those targeting Android 7.0.

If your app uses any of these intents, you should remove dependencies on them as soon as possible so that you can target Android 7.0 devices properly. The Android framework provides several solutions to mitigate the need for these implicit broadcasts. For example, the JobScheduler API provides a robust mechanism to schedule network operations when specified conditions, such as connection to an unmetered network, are met. You can even use JobScheduler to react to changes to content providers.

因此,最好使用JobScheduler API.

这是Example of JobScheduler.

标签:broadcastreceiver,android-jobscheduler,android,service,broadcast
来源: https://codeday.me/bug/20191026/1937818.html