4
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...

user1782267
  • 313
  • 4
  • 10
  • 20
  • 2
    Wow I hope you can't do it! If I've turned off 3G data on my phone it's because I don't want to use 3G data. It's not up to your app to turn it on behind my back!!! – John3136 Nov 01 '12 at 05:50
  • If there is no Wifi connected to my phone, then i am not able to send out email, so i have to turn on the 3g data send out the email and turn it off after email is sent... that is it... – user1782267 Nov 01 '12 at 05:59
  • 1
    Have you considered notifying the user that they don't have any connection and then offering to open the Settings via a button? That would be a more user-friendly way to accomplish what you want to do. – louielouie Nov 01 '12 at 06:00
  • 2
    My apps is an anti-theft application, and i bet the theft will never turn on the 3g data once he is notified... – user1782267 Nov 01 '12 at 06:02

5 Answers5

12

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"/>
Naveen
  • 483
  • 3
  • 8
  • 20
  • 5
    In AndroidL setMobileDataEnabled API is removed from ConnectivityManager and moved to TelephonyManager (setDataEnabled/getDataEnabled). Also the API is restricted in such way that it can only be accessible by System apps. – srs Nov 25 '14 at 16:59
5

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);
addy
  • 387
  • 1
  • 18
Rejinderi
  • 11,694
  • 2
  • 31
  • 40
  • 3
    Upvote to the thinking, but managers(mainly from testing background and clients don't try to understand these things, because some other apps have done it) – Shirish Herwade Apr 07 '15 at 09:18
  • 1
    java.lang.RuntimeException: Unable to start activity ComponentInfo{.....}: java.lang.SecurityException: Permission Denial: starting Intent { act=android.settings.DATA_ROAMING_SETTINGS cmp=com.android.phone/.Settings } from ProcessRecord{427dfb88 10208:co.akura.passio/u0a10020} (pid=10208, uid=10020) not exported from uid 1001 – djdance May 11 '15 at 15:39
2

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

Community
  • 1
  • 1
Amalan Dhananjayan
  • 2,277
  • 1
  • 34
  • 47
0
  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();
        }
    }
    }
    
Bryan P
  • 4,142
  • 5
  • 41
  • 60
katwal-Dipak
  • 3,523
  • 2
  • 23
  • 23
0

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);
tenten
  • 1,276
  • 2
  • 26
  • 54