Instead of registering receiver
in manifest
, register it in Activity
and pass interface
to interact on network state change
NetworkCallback.java
interface NetworkCallback{
void onStateChange();
}
ConnectionBroadReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionBroadReceiver extends BroadcastReceiver {
private NetworkCallback callback;
public ConnectionBroadReceiver(NetworkCallback callback){
this.callback = callback;
}
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
callback.onStateChange();
} else {
callback.onStateChange();
}
}
}
Now in your Ativity
public class MainActivity extends AppCompatActivity
{
private WebView webView;
public void onCreate(Bundle savedInstanceState){
// you code to set content view
webView = (WebView) findViewById(R.id.webview);
webView.postUrl(url, postData.getBytes());
registerReceiver(new ConnectionBroadReceiver(new NetworkCallback(){
@Override
public void onStateChange(){
webview.reload();
}
}),new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}
}
3
solved Declare receiver in mainactivity