How to use 3G Connection in Android Application in

2019-01-02 20:00发布

How to use 3G Connection in Android Application instead of Wi-fi?

I want to connect a 3G connection, is there any sample code to connect to 3G instead of Wi-fi?

9条回答
美炸的是我
2楼-- · 2019-01-02 20:39

This aplication activate 3G and Wifi connection, Giving preference to 3G!! Very useful http://www.redrails.com.br/2012/02/wireless-analyzer-for-android/

查看更多
谁念西风独自凉
3楼-- · 2019-01-02 20:45

@umka

  • i think, app can only reach to those hosts through HIPRI which it has requested, may be for other hosts(whose routes are not requested) is using the default network(MOBILE or WIFI).
  • On calling stopUsingNetworkFeature(), It will check -- is there any other app is using this network, if yes, then it will ignore your request to down this network feature.
  • one of the main purpose of HIPRI network is that - if wifi is on and an app wants to use mobile netwrok(3G)to reach the particular host, it can reach through HIPRI network.
查看更多
素衣白纱
4楼-- · 2019-01-02 20:46

Use connection manager and set network preference as you want.

for example:

dataManager  = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
dataManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
查看更多
骚的不知所云
5楼-- · 2019-01-02 20:51

There is a missing piece of code on @Northern Captain answer, the DNS lookup code.

Here is a working code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

    Log.d("NetworkDns", "Requesting CELLULAR network connectivity...");

    NetworkRequest request = new NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();

    connectivityManager.requestNetwork(request, new ConnectivityManager.NetworkCallback()
    {
        @Override
        public void onAvailable(final Network network)
        {
            Log.d("NetworkDns", "Got available network: " + network.toString());

            try
            {
                final InetAddress address = network.getByName("www.website.com");
                Log.d("NetworkDns", "Resolved host2ip: " + address.getHostName() + " -> " +  address.getHostAddress());
            }
            catch (UnknownHostException e)
            {
                e.printStackTrace();
            }

            Log.d("NetworkDns", "Do request test page from remote http server...");

            OkHttpClient okHttpClient = null;

            if(okHttpClient == null)
            {
                okHttpClient = new OkHttpClient.Builder()
                        .socketFactory(network.getSocketFactory())
                        .dns(new Dns() {
                            @Override
                            public List<InetAddress> lookup(String hostname) throws UnknownHostException {
                                if (network != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                    List<InetAddress> addresses = Arrays.asList(network.getAllByName(hostname));
                                    Log.d("NetworkDns", "List : " + addresses);
                                    return addresses;
                                }
                                return SYSTEM.lookup(hostname);
                            }
                        }).build();
            }

            Request request = new Request.Builder()
                    .url("http://www.website.com")
                    .build();
            try (Response response = okHttpClient.newCall(request).execute())
            {
                Log.d("NetworkDns", "RESULT:\n" + response.body().string());
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }

        }
    });
}
查看更多
姐姐魅力值爆表
6楼-- · 2019-01-02 20:52

I think that is not possible from Java. The system shuts down all mobile network based communication if connected to a wireless network. I think that you aren't allowed to start a 3G connection from you program.

查看更多
初与友歌
7楼-- · 2019-01-02 20:52

Inspired by code in this ticket and using some parts of it, here is service that establishes hipri mobile and keeps it running.

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

}

Here is how I start/stop it when needed. Note that it also gets locks on cpu and wifi so that it may run when the phone sleeps (screen only). Wifi is needed because my app is kind of bridge between wifi and mobile connections. You may not need it.

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

Don't forget to add service to you manifest file.

查看更多
登录 后发表回答