I want to download some data including json and image(binary data) whenever internet connectivity is available.
I have a full working code which can do that. The problem is I have written that code in custom application class. which downloads it and saves locally.But when app is launched the internet connectivity may not be available at that point of time.
So what I want to do is send the request and download the data whenever internet connectivity is detected and use that data by saving it in content provider locally. And the app will work even without an internet connection.
I am thinking of using broadcast receiver to download the same. But then it will be heavy task for a broadcast receiver to download the data. So now what I am finding out is I can check out internet connectivity in broadcast receiver and I will download the data from some other component. Which is the best practice to do so?
Is broadcast receiver stays around even when application is not on?
Which is the best practice to do so?
Best way is to use IntentService.
Start this service from your BroadcastReceiver. Via IntentService, all requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), so no worry about how long your task is.
Is broadcast receiver stays around even when application is not on?
Yes, if they are registered via manifest.
Helpful resources are
in the android developer guide mentioned you can Monitor for Changes in Connectivity
1st - you create a NetworkChangeReceiver class that is a BroadCastReceive , where you implement your code to download what you want :
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo activeNetwork = connMgr.getActiveNetworkInfo();
boolean isConnected = wifi != null &&
wifi.isConnected() ;
if (isConnected ) {
// Do something
Log.d("Netowk Available ", "Flag No 1");
}
}
}
2nd - you register your BroadCastReceiver
in the manifest file like the following :
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
来源:https://stackoverflow.com/questions/21250168/download-data-when-internet-connectivity-is-detected