[RESOLVIDO]Habilitar e desabilitar 3G[Android]

Boa Tarde, Pessoal

Estou fazendo um projeto q em um determinado tempo, preciso desabilitar o 3G e depois preciso habilitar de novo.

Alguém sabe como faço isso via codigo?

Obrigado

Tenta isso:
2.2-

Method dataConnSwitchmethod;
    Class telephonyManagerClass;
    Object ITelephonyStub;
    Class ITelephonyClass;

    TelephonyManager telephonyManager = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);

    if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED){
        isEnabled = true;
    }else{
        isEnabled = false;  
    }   

    telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
    Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
    getITelephonyMethod.setAccessible(true);
    ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
    ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());

    if (isEnabled) {
        dataConnSwitchmethod = ITelephonyClass
                .getDeclaredMethod("disableDataConnectivity");
    } else {
        dataConnSwitchmethod = ITelephonyClass
                .getDeclaredMethod("enableDataConnectivity");   
    }
    dataConnSwitchmethod.setAccessible(true);
    dataConnSwitchmethod.invoke(ITelephonyStub);

[]´s

Gingerbread

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

Tem que alterar o manifest

Fala, CidMiranda

Cara primeiramente obrigado pela força.

Cara oq esse código faz?

Pode me ajudar entender o código se não for pedir mto???

Obrigado.

Qual a versão do android que você vai usar?

A principio o 2.2

O primeiro código é para versão antes da 2.3 e o segundo para 2.3 ou superior.
Os métodos de “dados” Dataconnection e IConnectivityManager são escondidos na API do Android, não estando disponíveis para o desenvolvedor.
mas podem ser acessados via reflection.
Os dois códigos fazem a mesma coisa com versões do android diferentes.
Eles acessam o contexto do telefone. Além de desabilitar o 3g, wi-fi, também seria possível fazer ligações via aplicação.
[]´s

Dá uma olhada nesse post

http://developer.android.com/reference/android/net/ConnectivityManager.html

Certo.

Coloco esse codigo dentro de algum metodo, onde coloco esse codigo?

Meu codigo está dando erro no isEnabled e no context…

Obrigado

cria um método cmais ou menos assim:
private void setMobileData(Context context, boolean isEnabled) {

CidMiranda

Cara desculpa o trabalho q estou te dando cara…

Mas é q preciso entender oq estou fazendo, li os links q vc me mandou inclusive um é o mesmo codigo q vc me enviou.

Mas o problema é q não estou entendendo o codigo, ele ta habilitando, desabilitando?

qual o condição de acontecer algo.

Fiz o metodo assim…

[code]package br.com.sky;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.Context;
import android.telephony.TelephonyManager;

public class Conexao {
public void setMobileData(Context context, boolean enabled) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException{
Method dataConnSwitchmethod;
Class telephonyManagerClass;
Object ITelephonyStub;
Class ITelephonyClass;

        TelephonyManager telephonyManager = (TelephonyManager) context  
                .getSystemService(Context.TELEPHONY_SERVICE);  
      
        if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED){  
            enabled=true;  
        }else{  
            enabled = false;    
        }     
      
        telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());  
        Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");  
        getITelephonyMethod.setAccessible(true);  
        ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);  
        ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());  
      
        if (enabled==true) {  
            dataConnSwitchmethod = ITelephonyClass  
                    .getDeclaredMethod("disableDataConnectivity");  
        } else {  
            dataConnSwitchmethod = ITelephonyClass  
                    .getDeclaredMethod("enableDataConnectivity");     
        }  
        dataConnSwitchmethod.setAccessible(true);  
        dataConnSwitchmethod.invoke(ITelephonyStub); 
    }

}
[/code]

e aki chamo ele

[code]package br.com.sky;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class VideoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView web = new WebView(this);
WebSettings webSettings = web.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
web.loadUrl(“http://www.youtube.com/watch?v=AmgCYOBA5N8”);
setContentView(web);

    Conexao con = new Conexao();
    try {
		con.setMobileData(this, true);
	} catch (SecurityException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalArgumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (NoSuchMethodException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (InvocationTargetException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

}[/code]

E no manifest dei essa seguinte permissão.

Preciso entender oq estou fazendo.

Tem como comentar o codigo?

Obrigado

Fala Rotiv, achei um código comentado que vai te ajudar a entender.
Se você quiser habilitar passa true para o método boolean switchState(boolean enable), para desabilitar false.
Qualquer coisa é só postar :slight_smile:
[]´s

import java.lang.reflect.Method;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

// Needs the following permissions:
// - "android.permission.MODIFY_PHONE_STATE"

public final class DataConManager 
{
    private TelephonyManager m_telManager = null;
    private ConnectivityManager m_conManager = null;
 	
    // ------------------------------------------------------
    // ------------------------------------------------------
    public DataConManager(Context context)
    {
        try
        {
            // Get phone and connectivity services
            m_telManager = (TelephonyManager)context.getSystemService("phone");
            m_conManager = (ConnectivityManager)context.getSystemService("connectivity");
        }
        catch (Exception e)
        {
            m_telManager = null;
            m_conManager = null;
        }
    }

    // ------------------------------------------------------
    // ------------------------------------------------------
    boolean switchState(boolean enable) 
    {
    	boolean bRes = false;
    	
        // Data Connection mode (only if correctly initialized)
    	if (m_telManager != null)
        {
            try
            {
              // Will be used to invoke hidden methods with reflection
    	        Class cTelMan = null;
    	        Method getITelephony = null;
    	        Object oTelephony = null;
    	        Class cTelephony = null;
    	        Method action = null;
        		
    	        // Get the current object implementing ITelephony interface
    	        cTelMan = m_telManager.getClass();
    	        getITelephony = cTelMan.getDeclaredMethod("getITelephony");
    	        getITelephony.setAccessible(true);
    	        oTelephony = getITelephony.invoke(m_telManager);
    	        
    	        // Call the enableDataConnectivity/disableDataConnectivity method
    	        // of Telephony object
    	        cTelephony = oTelephony.getClass();
    	        if (enable)
    	        {
                    action = cTelephony.getMethod("enableDataConnectivity");
    	        }
    	        else
    	        {
    	            action = cTelephony.getMethod("disableDataConnectivity");
    	        }
    	        action.setAccessible(true);
    	        bRes = (Boolean)action.invoke(oTelephony);
            }
            catch (Exception e)
    	    {
                bRes = false;
            }
        }
        
    	return bRes;
    } 

    // ------------------------------------------------------
    // ------------------------------------------------------
    public boolean isEnabled()
    {
    	boolean bRes = false;
       
        // Data Connection mode (only if correctly initialized)
        if (m_conManager != null)
        {
            try       
            {
    	        // Get Connectivity Service state
    	        NetworkInfo netInfo = m_conManager.getNetworkInfo(0);
    	        
    	        // Data is enabled if state is CONNECTED
    	        bRes = (netInfo.getState() == NetworkInfo.State.CONNECTED);
            }
            catch (Exception e)
            {
    	        bRes = false;
            }
        }     
        
    	return bRes;
    }
}

Cara eu tava mexendo com isso e tava apanhando mto, ai eu descobri que eu consigo usar telas nativas pra fazer isso e essas telas podem ser chamadas de dentro da app,

			try {
					dialog.dismiss(); 
					final Intent intent = new Intent();
					intent.addCategory(Intent.ACTION_VIEW);
					final ComponentName cn = new ComponentName("com.android.phone", "com.android.phone.MobileNetworkSettings");
					intent.setComponent(cn);
					startActivity( intent);
				} catch (ActivityNotFoundException e) {
					//em alguns aparelhos não existe a opção de 3G
					Toast.makeText(ActPrincipal.this, "Configurações não disponiveis para este aparelho!", Toast.LENGTH_LONG).show();
				}

Pessoal,

Obrigado pela força de todos, consegui fazer funcionar da seguinte forma.

Não sei se é o jeito mais facil mas foi assim q eu fiz.

[code] public void onClick(View v) {
if (v.getId() == R.id.btnOk) {

        ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        android.net.NetworkInfo wifi = connec
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        android.net.NetworkInfo mobile = connec
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        String s = "Conexão: ";
        if (wifi.isConnected()) {
            s += "Wi-Fi";
        } else if (mobile.isConnected()) {
            s += "3G";
        }
        String ip = getLocalIpAddress();
        Toast.makeText(this, s, Toast.LENGTH_LONG).show();
        Toast.makeText(this, ip, Toast.LENGTH_LONG).show();

    } else {
        ToggleButton tb = (ToggleButton)v;
        if (!tb.isChecked()){
            disableApnList();
        } else {
            enableApnList();
        }
    }
}

private static final String SUFFIX = "apndroid";
private static final String ID = "_id";
private static final String APN = "apn";
private static final String TYPE = "type";
private static final Uri CONTENT_URI = Uri.parse("content://telephony/carriers");

private static final class ApnInfo {

    final long id;
    final String apn;
    final String type;

    public ApnInfo(long id, String apn, String type) {
        this.id = id;
        this.apn = apn;
        this.type = type;
    }
}

private void enableApnList() {
    List<ApnInfo> apns = selectApnInfo();
    
    final ContentResolver contentResolver = getContentResolver();
    for (ApnInfo apnInfo : apns) {
        ContentValues values = new ContentValues();
        String newApnName = removeSuffix(apnInfo.apn);
        values.put(APN, newApnName);
        String newApnType = removeComplexSuffix(apnInfo.type);
        if ("".equals(newApnType)) {
            values.putNull(TYPE);
        } else {
            values.put(TYPE, newApnType);
        }
        System.out.println("ENABLE>>>>"+ apnInfo.id +" - "+ newApnName +" - "+ newApnType);
        contentResolver.update(CONTENT_URI, values, ID + "=?", new String[] { String.valueOf(apnInfo.id) });

    }
}

private void disableApnList() {
    List<ApnInfo> apns = selectApnInfo();
    
    final ContentResolver contentResolver = this.getContentResolver();
    for (ApnInfo apnInfo : apns) {
        ContentValues values = new ContentValues();
        String newApnName = addSuffix(apnInfo.apn);
        values.put(APN, newApnName);
        String newApnType = addComplexSuffix(apnInfo.type);
        values.put(TYPE, newApnType);
        System.out.println("DISABLE>>>>"+ apnInfo.id +" - "+ newApnName +" - "+ newApnType);
        contentResolver.update(CONTENT_URI,
                values, ID + "=?",
                new String[] { String.valueOf(apnInfo.id) });
    }
}

private List<ApnInfo> selectApnInfo() {
    Cursor cursor = null;
    try {
        cursor = getContentResolver().query(CONTENT_URI, new String[] { ID, APN, TYPE }, null, null, null);

        if (cursor == null) return Collections.emptyList();

        List<ApnInfo> result = new ArrayList<ApnInfo>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            long id = cursor.getLong(0);
            String apn = cursor.getString(1);
            String type = cursor.getString(2);
            result.add(new ApnInfo(id, apn, type));
            System.out.println("GET>>>>"+ id +" - "+ type +" - "+ apn);
            cursor.moveToNext();
        }
        
        return result;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

public static String addSuffix(String currentName) {
    if (currentName == null) {
        return SUFFIX;
    } else {
        return currentName + SUFFIX;
    }
}

public String addComplexSuffix(String complexString) {
    if (complexString == null)
        return SUFFIX;

    StringBuilder builder = new StringBuilder(complexString.length());
    StringTokenizer tokenizer = new StringTokenizer(complexString, ",");
    while (tokenizer.hasMoreTokens()) {
        String str = tokenizer.nextToken().trim();
        if ("mms".equals(str)) {
            builder.append(str);
        } else {
            builder.append(addSuffix(str));
        }
        if (tokenizer.hasMoreTokens()) {
            builder.append(",");
        }
    }
    return builder.toString();
}

public static String removeSuffix(String currentName) {
    if (currentName.endsWith(SUFFIX)) {
        return currentName.substring(0, currentName.length() - SUFFIX.length());
    } else {
        return currentName;
    }
}

public static String removeComplexSuffix(String complexString){
    if (complexString == null) return "";

    StringBuilder builder = new StringBuilder(complexString.length());
    StringTokenizer tokenizer = new StringTokenizer(complexString, ",");
    while (tokenizer.hasMoreTokens()){
        builder.append(removeSuffix(tokenizer.nextToken().trim()));
        if (tokenizer.hasMoreTokens()){
            builder.append(",");
        }
    }
    return builder.toString();
}[/code]

Se funcionou está valendo.
[]´s