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);
        }
    }
 }

嗨,我正在开发一个Android应用程序,我想有一个检测到Wifi未连接到手机时自动打开移动数据的功能,因为我想确保无论何时都能发送电子邮件wifi是否连接...所以一旦检测到wifi未连接,则打开3G数据并发送电子邮件并关闭数据网络...

请问如何开启3G网络和关闭3G网络???互联网上的来源稀疏,我希望任何人都可以帮助我解决它...谢谢...

4

5 回答 5

12

希望此代码对您有所帮助,就我而言,它有效。

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 .

在清单中

    <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"/>
于 2013-07-02T05:27:11.087 回答
5

出于安全考虑,您不能以编程方式打开移动网络。

您唯一能做的就是通过显示设置来提示用户打开移动网络。

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);
于 2012-11-01T08:29:57.890 回答
2

适用于 Android 2.3 及更高版本

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);
}

这也需要以下许可。

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

请参考这个 链接

于 2013-07-02T06:18:00.157 回答
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. 这里 whatToDo 是一个布尔值,“true”表示开启 gprs,“false”表示关闭 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();
        }
    }
    }
    
于 2015-04-21T09:41:06.850 回答
0

对于禁用

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

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

dataMtd.setAccessible(false);

dataMtd.invoke(conman, false);

对于启用

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

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

dataMtd.setAccessible(true);

dataMtd.invoke(conman, true);
于 2016-04-01T10:18:32.157 回答