User can manually enable USB tethering from the phone settings, but what if your application wants to help the user enable it or force it to start?
Show the user tethering settings page
From within your application you can call activities defined by other apps, even the system ones, and the settings manager is not an exception. So, if you want the user to enable USB tethering on your device you can redirect him to the right settings page. This can be done simply by using an Intent:
Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.TetherSettings");
startActivity(intent);
On some phones, the ones without a mobile data capability I suppose, this settings section is "hidden" and not reachable by the user. Using this Intent will show it but the "Enable USB tethering" option could behave in strange ways.
Programmatically enable USB tethering
On ROOTED phones there's also a way to enable programmatically the USB tethering option (NOTE: This method seems to work on Android < 4.0). I haven't found a way to do it on a non rooted phone.
First of all add the following permissions to your AndroidManifest.xml:
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then using Java Reflection we can call the method to enable USB tethering:
public void switchOnTethering() {
Object systemService = getSystemService(Context.CONNECTIVITY_SERVICE);
for (Method method : systemService.getClass().getDeclaredMethods()) {
if (method.getName().equals("tether")) {
try {
method.invoke(systemService, "usb0");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
No comments:
Post a Comment