Search code examples
androidandroid-studioreact-nativemobile-application

problem happen while enabling or disabling the mobile data in android


I have a exception happen while I run this source:

public void setMobileDataState(boolean mobileDataEnabled) {
    try {
        TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        Method setMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
        if (null != setMobileDataEnabledMethod) {
            setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);

        }
    } catch (Exception ex) {
        Log.e(TAG, "Error setting mobile data state", ex);
    }
}

Exception:

java.lang.reflect.InvocationTargetException


Solution

  • I'm using this piece of code in my application. It is working fine for me. Hope this helps you.

    For Checking if data is enabled or not you can call getMobileDataState()

    For Setting it to Enable or Disable you can call setMobileDataState(boolean). Pass true to Enable Mobile Data and false to Disable Mobile Data

       /*Changing mobile data state -  True to turn it ON*/
    public void setMobileDataState(boolean mobileDataEnabled) {
    
        try {
            final ConnectivityManager conman = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            final Class<?> conmanClass = Class.forName(conman.getClass().getName());
            final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
            iConnectivityManagerField.setAccessible(true);
            final Object iConnectivityManager = iConnectivityManagerField.get(conman);
            final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
            final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
            setMobileDataEnabledMethod.setAccessible(true);
            setMobileDataEnabledMethod.invoke(iConnectivityManager, mobileDataEnabled);
        }
        catch (Exception ex) {
            Toasty.error(Main.this, "Exception: "+ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /* getting mobile data current state - returns True if ON*/
    public boolean getMobileDataState() {
        try {
            TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            Method getMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("getDataEnabled");
            if (null != getMobileDataEnabledMethod) {
                boolean mobileDataEnabled = (Boolean) getMobileDataEnabledMethod.invoke(telephonyService);
                return mobileDataEnabled;
            }
        }
        catch (Exception ex) {
            Toasty.error(Main.this, "Exception: "+ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return false;
    }
    

    Call this where you want to Turn On Mobile data

    setMobileDataState(true);
    

    Call this where you want to Turn OFF Mobile data

    setMobileDataState(false);
    

    Update:

    You need to add MODIFY_PHONE_STATE permission in your Manifest.xml

    if (ActivityCompat.checkSelfPermission(context,
                        android.Manifest.permission.MODIFY_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
    
         ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.MODIFY_PHONE_STATE}, 101);
    
         } else {
                    setMobileDataEnabled(true);
         }
    

    Then in onRequestPermissionsResult

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 101) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setMobileDataEnabled(true);
            } else {
                Toasty.error(this, "Permission required to perform this action..", Toast.LENGTH_SHORT).show();
    
                showAlert();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    

    ShowAlertDialog

    private void showAlert(){
                        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                        dialog.setCancelable(false);
                        dialog.setTitle("Permissions");
                        dialog.setMessage("Please allow this permission in Settings.");
                        dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent();
                                intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        });
                        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(new Intent(Settings.this, Settings.class));
                                finish();
                            }
                        });
                        dialog.show();
    }