How to enable mobile data on/off programmatically
You cannot access mobile data on / off programmaticaly above android 4.4 .It have been made stopped for security reasons ,instead you can ask the user using a dialog to enable the mobile data and then if he enable you can do your task.
Enable/disable data connection in android programmatically
This code sample should work for android phones running gingerbread and higher:
private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
connectivityManagerField.setAccessible(true);
final Object connectivityManager = connectivityManagerField.get(conman);
final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
}
Dont forget to add this line to your manifest file
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
Disable/Enabling mobile data programmatically in Android
I am trying to enable/disable mobile data.
First, is it possible to implement this?
No, that's not possible to achieve by third-party apps. Enabling/disabling mobile data should be done through system Settings app UI.
What you can do is to provide an instruction to end user on how to enable/disable mobile data and direct them to Settings app.
Related Topics
Android: How to Use Onbackpressed() with Toast
How to Get Camera Result as a Uri in Data Folder
Add and Remove Views in Android Dynamically
Onactivityresult() Called Prematurely
Open Link of Google Play Store in Mobile Version Android
Background Service with Location Listener in Android
How to Create Directory Automatically on Sd Card
How to Add a Button to Preferencescreen
Slowing Speed of Viewpager Controller in Android
Don't Reload Application When Orientation Changes
Google Sign in Not Working After Publishing in Play Store
Android Studio - Local Path Doesn't Exist
Get Contact Info from Android Contact Picker
How to Set Image Button Backgroundimage for Different State
How to Set Onclicklistener on a Radiobutton in Android