Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've done an extensive search on this topic recently and must tell there is no simple solution to this problem on modern Android versions, unless you run your app as root.</p> <p>I found a simple, yet a bit limited, workaround though: 3G connectivity is active only if WiFi is down, so each time you are about to initialize a network connection, you must check if WiFi is up and connected. Below is some code for your sample activity:</p> <pre><code>public class MyActivity extends Activity { boolean enable3g = false; public void onCreate() { setContentView(R.layout.my_layout); Button enable3gButton = (Button) findViewById(R.id.button3g); enable3gButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MyActivity.this.enable3g = !MyActivity.this.enable3g; } }); if (enable3g || isWifiConnected()) { // do your stuff that requires network access here } } public boolean isWifiConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected(); } } </code></pre> <p>In AndroidManifest you need <code>ACCESS_NETWORK_STATE</code> permission (and a declaration of your activity of course):</p> <pre><code>&lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; &lt;application .....&gt; &lt;activity android:name="MyActivity" /&gt; </code></pre> <p>If WiFi is not connected (the <code>isWifiConnected()</code> method returns <code>false</code>), do not start to connect. An existing TCP connection cannot "jump" from one network to another so it will just time out if WiFi connectivity is broken, making the solution quite safe.</p> <p>The limitation is, that you must be able to control your application's connections. If you are using WebView, or some 3rd-party piece of software, it may get tricky.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload