I had the same problem, I did something similar. It worked for me, I hope this helps.
public class NewActivity extends AppCompatActivity { final static String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; IntentFilter intentFilter; MyReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new); intentFilter = new IntentFilter(); intentFilter.addAction(CONNECTIVITY_ACTION); receiver = new MyReceiver(); if(checkForInternet()){ loadData(); }else{ updateUI(); } } @Override protected void onResume() { super.onResume(); registerReceiver(receiver, intentFilter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(receiver); } // Self explanatory method public boolean checkForInternet() { ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } void loadData(){ // do sth } void updateUI(){ // No internet connection, update the ui and warn the user } private class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String actionOfIntent = intent.getAction(); boolean isConnected = checkForInternet(); if(actionOfIntent.equals(CONNECTIVITY_ACTION)){ if(isConnected){ loadData(); }else{ updateUI(); } } } } }
Do not add the receiver to the manifest so that it only works in this action.
Tahir ferli
source share