简体   繁体   中英

How to turn on 3G mobile data programmatically in Android?

package com.testing.connection;

import android.app.Activity;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ConnectionActivity extends Activity implements OnClickListener{

    Button press;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        press = (Button)findViewById(R.id.button1);
        press.setOnClickListener(this);
    }

    public void onClick(View view){
        ConnectivityManager mgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);

        boolean is3G = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
        boolean isWifi = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();

        if(isWifi){
            Toast.makeText(this, "WiFi connected...", Toast.LENGTH_LONG).show();
            sendMail();
        }
        else{
            //**Turn on Mobile Data
            //**Then sendMail()
            //**Turn off Mobile Data
        }
    }

    public void sendMail() throws MessagingException{

        String host = "smtp.gmail.com";
        String password = "abc123";
        String from = "testing@gmail.com";
        String toAddress = enterEmail.getText().toString();

        Properties properties = System.getProperties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtps.auth", true);
        properties.put("mail.smtp.starttls.enable", true);
        Session session = Session.getInstance(properties, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, toAddress);
        message.setSubject("Anti-Theft Attachment");

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("Your email address is saved as backup email in Anti-Theft Application");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        try{
            Transport transport = session.getTransport("smtps");
            transport.connect(host, from, password);
            transport.sendMessage(message, message.getAllRecipients());
            System.out.println("Mail Sent Successfully");
            transport.close();
        } catch (SendFailedException sfe){
            System.out.println(sfe);
        }
    }
 }

Hi, I am developing an Android application, and I would like to have the function of turn on mobile data automatically once the Wifi is detected not connected to the phone, because I would like to make sure the email can be sent out no matter the Wifi is connected or not... So once the wifi is detected not connected, the 3G data is turned on and the email is sent out and the data network turned off...

May I know how to perform the turn on 3G network and turn off 3G network??? The source on Internet is sparse and I hope anyone can help me to solve it... Thanks...

Hope this code will help you ,In my case it worked.

ConnectivityManager dataManager;
dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
dataMtd.setAccessible(true);
dataMtd.invoke(dataManager, true);        //True - to enable data connectivity .

in Manifest

    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

Due to security concerns you are not allowed to turn on mobile network programmatically.

The only thing you can do is to prompt the user to turn on the mobile network by displaying the settings.

Intent intent=new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
ComponentName cn = new ComponentName("com.android.phone","com.android.phone.Settings");
intent.setComponent(cn);
startActivity(intent);

For Android 2.3 and Above

private void setMobileDataEnabled(Context context, boolean enabled) {
    final ConnectivityManager conman = (ConnectivityManager) context.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, enabled);
}

This also requires the following permission.

 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

Please refer this Link

  1. "android.permission.ACCESS_NETWORK_STATE"
  2. "android.permission.ACCESS_WIFI_STATE"
  3. "android.permission.CHANGE_WIFI_STATE"
  4. "android.permission.CHANGE_NETWORK_STATE"
  5. Here whatToDo is a boolean value, "true" for turning gprs on and "false" for turning off the gprs.

     public class TurnDataOn { public static boolean isWifiOn(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE); boolean wifiEnabled = wifiManager.isWifiEnabled(); Log.e("isWifiOn", String.valueOf(wifiEnabled)); return wifiEnabled; } public static boolean isWifiConnected(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); boolean wifiConnected = wifiInfo.getState() == NetworkInfo.State.CONNECTED; Log.e("isWIFIConnected", String.valueOf(wifiConnected)); return wifiConnected; } public static boolean isGprsConnected(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); boolean mobileConnected = mobileInfo.getState() == NetworkInfo.State.CONNECTED; Log.e("ISGPRSConnected", String.valueOf(mobileConnected)); return mobileConnected; } public static void toggleGprs(Context context, boolean whatToDo) { ConnectivityManager conman = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); @SuppressWarnings("rawtypes") Class conmanClass = null; try { conmanClass = Class.forName(conman.getClass().getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } Field iConnectivityManagerField = null; try { iConnectivityManagerField = conmanClass.getDeclaredField("mService"); } catch (NoSuchFieldException e) { e.printStackTrace(); } iConnectivityManagerField.setAccessible(true); Object iConnectivityManager = null; try { iConnectivityManager = iConnectivityManagerField.get(conman); } catch (IllegalAccessException e) { e.printStackTrace(); } @SuppressWarnings("rawtypes") Class iConnectivityManagerClass = null; try { iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } @SuppressWarnings("unchecked") Method setMobileDataEnabledMethod = null; try { setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); } catch (NoSuchMethodException e) { e.printStackTrace(); } setMobileDataEnabledMethod.setAccessible(true); try { setMobileDataEnabledMethod.invoke(iConnectivityManager, whatToDo); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } 

For disable

final ConnectivityManager conman = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);

Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);

dataMtd.setAccessible(false);

dataMtd.invoke(conman, false);

For Enable

final ConnectivityManager conman = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);

Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);

dataMtd.setAccessible(true);

dataMtd.invoke(conman, true);
  public void onToggleClicked(View view) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    // Is the toggle on?
    boolean on = ((ToggleButton) view).isChecked();

    if (on) {

        // Enable data
        ConnectivityManager dataManager;
        dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
        dataMtd.setAccessible(true);
        dataMtd.invoke(dataManager, true);        //True - to enable data connectivity .


    } else {
        // Disable data

        ConnectivityManager dataManager;
        dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
        dataMtd.setAccessible(true);
        dataMtd.invoke(dataManager, false);        //True - to enable data connectivity .


    }
}

That worked for me on 4.4.3 bros Use a toggle or switch bros

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM