summaryrefslogtreecommitdiff
path: root/src/jp/example/tethering/TetherCli.java
blob: 4cf333647704f7a2a35992ed1aec4a4105a89e6a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package jp.example.tethering;

import android.content.Context;
import android.os.Looper;

import java.lang.reflect.Method;

/**
 * Runs as a separate root process via:
 *
 *   CLASSPATH=<this apk> /system/bin/app_process /system/bin \
 *       jp.example.tethering.TetherCli usb true
 *
 * A normal app cannot call setUsbTethering() (it needs TETHER_PRIVILEGED),
 * but uid 0 can.
 */
public class TetherCli {
    public static void main(String[] args) {
        String mode = args.length > 0 ? args[0] : "usb";
        boolean enable = args.length < 2 || "true".equalsIgnoreCase(args[1]);
        try {
            Looper.prepareMainLooper();
            Class<?> at = Class.forName("android.app.ActivityThread");
            Object thread = at.getMethod("systemMain").invoke(null);
            Context ctx = (Context) at.getMethod("getSystemContext").invoke(thread);

            if ("usb".equals(mode)) {
                Object cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
                Method m = cm.getClass().getMethod("setUsbTethering", boolean.class);
                m.invoke(cm, enable);
                System.out.println("OK usb " + enable);
            } else if ("wifi".equals(mode)) {
                Object wm = ctx.getSystemService(Context.WIFI_SERVICE);
                Method m = wm.getClass().getMethod("setWifiApEnabled",
                        android.net.wifi.WifiConfiguration.class, boolean.class);
                m.invoke(wm, null, enable);
                System.out.println("OK wifi " + enable);
            } else if ("bt".equals(mode)) {
                Object cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
                Method m = cm.getClass().getMethod("setBluetoothTethering", boolean.class);
                m.invoke(cm, enable);
                System.out.println("OK bt " + enable);
            } else {
                System.out.println("unknown mode " + mode);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
        try {
            Thread.sleep(1200);
        } catch (InterruptedException ignored) {
        }
    }
}