public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
this.registerReceiver(mDATAStateChangedReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));}
@Override public void onBackPressed() { unregisterReceiver(mDATAStateChangedReceiver); // this will unregister Receiver this.finish(); // this will finish ThisActivity super.onBackPressed(); }private BroadcastReceiver mDATAStateChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean mobileDataEnabled = false; // Assume disabled try { Class cmClass = Class.forName(cm.getClass().getName()); Method method = cmClass.getDeclaredMethod("getMobileDataEnabled"); method.setAccessible(true); // Make the method callable // get the setting for "mobile data" mobileDataEnabled = (Boolean)method.invoke(cm); } catch (Exception e) { // Some problem accessible private API } if(mobileDataEnabled == false){//mobile data is disconnected, do whatever you want here);} else {info10.setText(//mobile data is connected, do whatever you want here); } } }; }
How to update "Mobile data" state using a BroadcastReceiver
This BroadcastReceiver will trigger anytime "Mobile data" disconnects or connects.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment