How can I turn on/ off mobile data in android studio using a button?(should support >=Android5.0)

86 Views Asked by At

Below is my mainActivity class and also I enabled CHANGE_NETWORKSTATE, INTERNET, ACCESS_NETWORKSTATE permissions in Manifest file.

For below code, I tested, (when I am pressing the button nothing happens)

A big thanks if someone can figure out the bug here:)

NOTE: My wifi should remain ON before and after this.

public class MainActivity extends AppCompatActivity {

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.download);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Context context = getApplicationContext();
                NetworkRequest.Builder request = new NetworkRequest.Builder();
                request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
                request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
                ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                connectivityManager.requestNetwork(request.build(), new ConnectivityManager.NetworkCallback());

            }
        });
    }
}
0

There are 0 best solutions below