I have a Main Activity, which holds 1 fragment. The fragment is responsible for drawing the UI, running an Async task, etc. All of this requires an internet connection. Now when I first launch my app I check whether there is an internet connection or not through a method:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting());
}
If there is no network connection, the activity starts the fragment, but I've made it so that without an internet connection nothing shows (since there is nothing to show because I am downloading content from an online database).
I want to implement a broadcast receiver, which would restart the fragment somehow, when there is an internet connection available. So far I have a broadcast receiver as an Inner class in my Main activity:
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getExtras() != null) {
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni != null && ni.isConnectedOrConnecting()) {
Toast.makeText(context, "internet ++", Toast.LENGTH_LONG).show();
//this is where the fragment needs to be somehow reinstantiated
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Toast.makeText(context, "internet --", Toast.LENGTH_LONG).show();
}
}
}
};
I've tried to make the broadcast receiver an outer class, but then I cannot do anything to the fragment.. When it is an Inner class, nothing happens with the code from the broadcast receiver. I've reviewed a lot of similar questions, but nothing seems to work from me.
So the question at hand would be: How do I refresh a fragment inside an activity, when the internet connection becomes available while the app is running?