Reputation: 7214
I am working on an App that will upload all my database records to server sequentially in the background when the device is connected to the internet.
For this, i have written a BroadcastReceiver
that will listen for network connection. When this receiver is triggered I am starting background service for uploading the records.
Here is my code.
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));
}
}
}
Now my doubt is
1. Can I do the same using JobScheduler?
2. What is the better(mine or the one using JobScheduler) approach and Why ?
Upvotes: 4
Views: 7544
Reputation: 406
I don't know which action you are using for the BroadcastReceiver but I guess it is the CONNECTIVITY_CHANGE action. If you use it read the following text from the side about 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.
So it's better to use the JobScheduler API.
Here is an Example of JobScheduler.
Upvotes: 5