¿Cómo usar la conexión 3G en la aplicación Android en lugar de Wi-fi?

¿Cómo usar la conexión 3G en la aplicación Android en lugar de Wi-fi?

Quiero conectar una conexión 3G, ¿hay algún código de ejemplo para conectarse a 3G en lugar de Wi-fi?

La aplicación "Mi cuenta" de T-Mobile lo hace, si está conectado a una conexión WiFi, le indica que su programa no funcionará con WiFi y luego le preguntará al usuario si desea desactivar la conexión WiFi. Si elige " No ", entonces la aplicación sale, si elige" Sí ", la aplicación desactiva su conexión WiFi y luego continúa con la puesta en marcha.

Creo que este es un buen modelo a seguir, se asegurará de que su aplicación no se está ejecutando a través de WiFi y permite al usuario decidir si quieren desactivar WiFi o no. Una mejora en este modelo sería volver a encender Wi-Fi cuando el usuario navega lejos de su aplicación.

No he probado el código siguiente, pero parece que debería funcionar (modificado desde aquí )

Utilice los permisos siguientes en su manifiesto

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

Y aquí hay algún código real para activar / desactivar wifi

 private WifiManager wifiManager; @Override public void onCreate(Bundle icicle) { .................... wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); if(wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(false); } else { wifiManager.setWifiEnabled(true); } } 

Si no desea ir por esa ruta parece que podría ser capaz de decirle al teléfono que preferiría utilizar la red de datos móviles en lugar de la red wifi.

El Android ConnectivityManager ofrece una función setNetworkPreference . Esta función no está realmente documentada, ya que puede saber si hace clic en el enlace. Sin embargo, sería paly alrededor con él, porque las constantes que se definen parecen sugerir que puede establecer esto a TYPE_MOBILE o TYPE_WIFI y hay una constante DEFAULT_NETWORK_PREFERENCE así como que se define como 0x00000001 que es el mismo que TYPE_WIFI. Intente obtener acceso a un ConnectivityManager llamando al

 Context.getSystemService(Context.CONNECTIVITY_SERVICE); 

Y luego intente usar la función setNetworkPreference ().

No parece requerir permisos en el manifiesto, pero puede requerir el permiso CHANGE_NETWORK_STATE o algo similar a esas líneas.

Si usted hace una demanda a la función setNetworkPreference, probablemente sería mejor también establecer la preferencia de red de nuevo a sus valores originales (recibidos de getNetworkPreference)

Espero que esto ayude.

 /** * Enable mobile connection for a specific address * @param context a Context (application or activity) * @param address the address to enable * @return true for success, else false */ private boolean forceMobileConnectionForAddress(Context context, String address) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (null == connectivityManager) { Log.debug(TAG_LOG, "ConnectivityManager is null, cannot try to force a mobile connection"); return false; } //check if mobile connection is available and connected State state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); Log.debug(TAG_LOG, "TYPE_MOBILE_HIPRI network state: " + state); if (0 == state.compareTo(State.CONNECTED) || 0 == state.compareTo(State.CONNECTING)) { return true; } //activate mobile connection in addition to other connection already activated int resultInt = connectivityManager.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableHIPRI"); Log.debug(TAG_LOG, "startUsingNetworkFeature for enableHIPRI result: " + resultInt); //-1 means errors // 0 means already enabled // 1 means enabled // other values can be returned, because this method is vendor specific if (-1 == resultInt) { Log.error(TAG_LOG, "Wrong result of startUsingNetworkFeature, maybe problems"); return false; } if (0 == resultInt) { Log.debug(TAG_LOG, "No need to perform additional network settings"); return true; } //find the host name to route String hostName = StringUtil.extractAddressFromUrl(address); Log.debug(TAG_LOG, "Source address: " + address); Log.debug(TAG_LOG, "Destination host address to route: " + hostName); if (TextUtils.isEmpty(hostName)) hostName = address; //create a route for the specified address int hostAddress = lookupHost(hostName); if (-1 == hostAddress) { Log.error(TAG_LOG, "Wrong host address transformation, result was -1"); return false; } //wait some time needed to connection manager for waking up try { for (int counter=0; counter<30; counter++) { State checkState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); if (0 == checkState.compareTo(State.CONNECTED)) break; Thread.sleep(1000); } } catch (InterruptedException e) { //nothing to do } boolean resultBool = connectivityManager.requestRouteToHost(ConnectivityManager.TYPE_MOBILE_HIPRI, hostAddress); Log.debug(TAG_LOG, "requestRouteToHost result: " + resultBool); if (!resultBool) Log.error(TAG_LOG, "Wrong requestRouteToHost result: expected true, but was false"); return resultBool; } 

Y esto para calcular la dirección de host:

 /** * This method extracts from address the hostname * @param url eg. http://some.where.com:8080/sync * @return some.where.com */ public static String extractAddressFromUrl(String url) { String urlToProcess = null; //find protocol int protocolEndIndex = url.indexOf("://"); if(protocolEndIndex>0) { urlToProcess = url.substring(protocolEndIndex + 3); } else { urlToProcess = url; } // If we have port number in the address we strip everything // after the port number int pos = urlToProcess.indexOf(':'); if (pos >= 0) { urlToProcess = urlToProcess.substring(0, pos); } // If we have resource location in the address then we strip // everything after the '/' pos = urlToProcess.indexOf('/'); if (pos >= 0) { urlToProcess = urlToProcess.substring(0, pos); } // If we have ? in the address then we strip // everything after the '?' pos = urlToProcess.indexOf('?'); if (pos >= 0) { urlToProcess = urlToProcess.substring(0, pos); } return urlToProcess; } /** * Transform host name in int value used by {@link ConnectivityManager.requestRouteToHost} * method * * @param hostname * @return -1 if the host doesn't exists, elsewhere its translation * to an integer */ private static int lookupHost(String hostname) { InetAddress inetAddress; try { inetAddress = InetAddress.getByName(hostname); } catch (UnknownHostException e) { return -1; } byte[] addrBytes; int addr; addrBytes = inetAddress.getAddress(); addr = ((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8 ) | (addrBytes[0] & 0xff); return addr; } 

Y el siguiente permiso se debe agregar a AndroidManifest.xml

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

Funciona sólo con Android 2.2 y superiores, probado tanto en Nexus One como en LG Optimus, otros teléfonos que no conozco porque algún método de ConnectivityMananger es específico del proveedor. Después de 15-20 segundos de inactividad, la red móvil se desconecta automáticamente.

Creo que no es posible desde Java. El sistema apaga toda la comunicación basada en la red móvil si está conectada a una red inalámbrica. Creo que no se le permite iniciar una conexión 3G desde su programa.

Utilice el administrador de conexiones y establezca la preferencia de red como desee. buena suerte

Por ejemplo: dataManager = (ConnectivityManager) getSystemService (CONNECTIVITY_SERVICE); DataManager.setNetworkPreference (ConnectivityManager.TYPE_MOBILE);

Aquí está el código que funciona en API 21+ (Lollipop, Marshmallow ..). Yo prefiero usar OkHttp con Network.getSocketFactory () , pero Network.openURLConnection () también funciona bien.

 private void doTest() { display("Requesting CELLULAR network connectivity..."); ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkRequest request = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(); connectivityManager.requestNetwork(request, new ConnectivityManager.NetworkCallback() { /** * Called when the framework connects and has declared a new network ready for use. * This callback may be called more than once if the {@link Network} that is * satisfying the request changes. * * This method will be called on non-UI thread, so beware not to use any UI updates directly. * * @param network The {@link Network} of the satisfying network. */ @Override public void onAvailable(final Network network) { display("Got available network: " + network.toString()); try { final InetAddress address = network.getByName("navalclash.com"); display("Resolved host2ip: " + address.getHostName() + " -> " + address.getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } display("Do request test page from remote http server..."); if(okHttpClient == null) { okHttpClient = new OkHttpClient.Builder().socketFactory(network.getSocketFactory()).build(); } Request request = new Request.Builder() .url("http://navalclash.com") .build(); try (Response response = okHttpClient.newCall(request).execute()) { display("RESULT:\n" + response.body().string()); } catch (Exception ex) { ex.printStackTrace(); } } }); } 

Esta aplicación activa la conexión 3G y Wifi, dando preferencia a 3G !! Muy útil http://www.redrails.com.br/2012/02/wireless-analyzer-for-android/

Inspirado por el código en este boleto y utilizando algunas partes de él, aquí es el servicio que establece hipri móvil y lo mantiene en funcionamiento.

 import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.atomic.AtomicBoolean; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo.State; import android.os.IBinder; import android.util.Log; public class HipriService extends Service { private AtomicBoolean enabledMobile = new AtomicBoolean(false); public boolean enableMobileConnection() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (null == cm) { Log.d(TAG, "ConnectivityManager is null, cannot try to force a mobile connection"); return false; } /* * Don't do anything if we are connecting. On the other hands re-new * connection if we are connected. */ State state = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); Log.d(TAG, "TYPE_MOBILE_HIPRI network state: " + state); if (0 == state.compareTo(State.CONNECTING)) return true; /* * Re-activate mobile connection in addition to other connection already * activated */ int resultInt = cm.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableHIPRI"); //Log.d(TAG, "startUsingNetworkFeature for enableHIPRI result: " + resultInt); //-1 means errors // 0 means already enabled // 1 means enabled // other values can be returned, because this method is vendor specific if (-1 == resultInt) { Log.e(TAG, "Wrong result of startUsingNetworkFeature, maybe problems"); return false; } if (0 == resultInt) { Log.d(TAG, "No need to perform additional network settings"); return true; } return requestRouteToHost(this, Uploader.ServerAddress); } private Thread pingerThread = null; private void startMobileConnection() { enabledMobile.set(true); pingerThread = new Thread(new Runnable() { @Override public void run() { while (enabledMobile.get()) { /* * Renew mobile connection. No routing setup is needed. This * should be moved to 3g monitoring service one day. */ enableMobileConnection(); try { Thread.sleep(1000); } catch (InterruptedException e) { // do nothing } } } }); pingerThread.start(); } private void stopMobileConnection() { enabledMobile.set(false); disableMobileConnection(); pingerThread.interrupt(); pingerThread = null; } public void disableMobileConnection() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cm.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableHIPRI"); } public final static int inetAddressToInt(InetAddress inetAddress) { byte[] addrBytes; int addr; addrBytes = inetAddress.getAddress(); addr = ((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8) | (addrBytes[0] & 0xff); return addr; } public final static InetAddress lookupHost(String hostname) { try { return InetAddress.getByName(hostname); } catch (UnknownHostException e) { return null; } } private boolean requestRouteToHost(Context context, String hostname) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (null == cm) { Log.d(TAG, "ConnectivityManager is null, cannot try to force a mobile connection"); return false; } /* Wait some time needed to connection manager for waking up */ try { for (int counter = 0; enabledMobile.get() && counter < 30; counter++) { State checkState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); Log.i(TAG, "Waiting for mobile data on. State " + checkState); if (0 == checkState.compareTo(State.CONNECTED)) break; Thread.sleep(1000); } } catch (InterruptedException e) { //nothing to do } if (!enabledMobile.get()) { Log.d(TAG, "Mobile data is turned off while waiting for routing."); return false; } State checkState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); if (0 != checkState.compareTo(State.CONNECTED)) { Log.e(TAG, "Mobile data is still turned off after 30 sec of waiting."); return false; } Log.i(TAG, "Adding routing for " + hostname); InetAddress inetAddress = lookupHost(hostname); if (inetAddress == null) { Log.e(TAG, "Failed to resolve " + hostname); return false; } int hostAddress = inetAddressToInt(inetAddress); boolean resultBool = cm.requestRouteToHost(ConnectivityManager.TYPE_MOBILE_HIPRI, hostAddress); Log.d(TAG, "requestRouteToHost result: " + resultBool); if (!resultBool) Log.e(TAG, "Wrong requestRouteToHost result: expected true, but was false"); return resultBool; } @Override public void onCreate() { super.onCreate(); startMobileConnection(); } @Override public void onDestroy() { stopMobileConnection(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } } 

Aquí es cómo iniciarlo / detenerlo cuando sea necesario. Tenga en cuenta que también obtiene bloqueos en la CPU y wifi para que pueda ejecutarse cuando el teléfono duerme (sólo pantalla). Wifi es necesario porque mi aplicación es una especie de puente entre wifi y conexiones móviles. Es posible que no lo necesite.

 public void startMobileData() { if (!enabledMobile.get()) { enabledMobile.set(true); WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "Wifi Wakelock"); wifiLock.acquire(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); partialLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "3G Wakelock"); partialLock.acquire(); startService(new Intent(this, HipriService.class)); } } public void stopMobileData() { if (enabledMobile.get()) { enabledMobile.set(false); Log.i(TAG, "Disabled mobile data"); stopService(new Intent(this, HipriService.class)); if (partialLock != null) { partialLock.release(); partialLock = null; } if (wifiLock != null) { wifiLock.release(); wifiLock = null; } } } 

No te olvides de añadir servicio a tu archivo de manifiesto.

@umka

  • Creo que la aplicación sólo puede llegar a los hosts a través de HIPRI que ha solicitado, puede ser para otros hosts (cuyas rutas no se solicitan) está utilizando la red por defecto (MÓVIL o WIFI).
  • Al llamar a stopUsingNetworkFeature () , comprobará – si hay alguna otra aplicación que esté utilizando esta red, en caso afirmativo, ignorará su solicitud en esta función de red.
  • Uno de los principales propósitos de la red HIPRI es que – si wifi está encendido y una aplicación quiere utilizar netwrok móvil (3G) para llegar al host en particular, puede llegar a través de la red HIPRI.
  • Mover la carpeta predeterminada de configuración AVD (.android)
  • Configuración de la aceleración de la máquina virtual para Android
  • Emular Nexus 7
  • Desarrollo de una "aplicación de sistema" con el emulador Android Studio / AVD
  • "El objeto real ha sido eliminado" en logcat
  • Android: Cómo eliminar preferencias compartidas en otro paquete
  • La aplicación Android GPS no funciona en Emulator
  • Uso de Google Play Games Services en el emulador
  • Error de la instantánea del emulador de Android
  • El emulador de Android pierde conexión a Internet después de un período de tiempo (inactivo o activo)
  • Instalar una aplicación de Google Play en Emulator
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.