summaryrefslogtreecommitdiff
path: root/src/jp/example/tethering/MainActivity.java
blob: 4bf9a18b292bb8a135dbbbf1f19e7b49fe5c795e (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package jp.example.tethering;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.graphics.Color;
import java.net.NetworkInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;

public class MainActivity extends Activity {
    private static final String PREFS = "tethering";
    private static final String KEY_AUTO = "auto_usb";
    private static final String KEY_MANUAL_OFF = "manual_off";

    private TextView status;
    private Button toggle;
    private CheckBox auto;
    private SharedPreferences prefs;
    private final Handler handler = new Handler(Looper.getMainLooper());
    private boolean lastOn = false;
    private boolean busy = false;

    private final Runnable refresh = new Runnable() {
        @Override
        public void run() {
            refreshStatus();
            handler.postDelayed(this, 3000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prefs = getSharedPreferences(PREFS, MODE_PRIVATE);

        ScrollView scroll = new ScrollView(this);
        LinearLayout root = new LinearLayout(this);
        root.setOrientation(LinearLayout.VERTICAL);
        int p = dp(20);
        root.setPadding(p, p, p, p);
        scroll.addView(root);

        TextView title = new TextView(this);
        title.setText("テザリング");
        title.setTextSize(28);
        title.setGravity(Gravity.CENTER_HORIZONTAL);
        root.addView(title);

        status = new TextView(this);
        status.setTextSize(18);
        status.setPadding(0, dp(16), 0, dp(16));
        status.setGravity(Gravity.CENTER_HORIZONTAL);
        root.addView(status);

        toggle = new Button(this);
        toggle.setTextSize(22);
        toggle.setFocusable(true);
        toggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setUsb(!lastOn);
            }
        });
        root.addView(toggle, new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, dp(72)));

        auto = new CheckBox(this);
        auto.setText("USB接続時に自動でON");
        auto.setTextSize(16);
        auto.setFocusable(true);
        auto.setChecked(prefs.getBoolean(KEY_AUTO, true));
        auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                prefs.edit().putBoolean(KEY_AUTO, isChecked).apply();
                if (isChecked) {
                    prefs.edit().putBoolean(KEY_MANUAL_OFF, false).apply();
                }
            }
        });
        root.addView(auto);

        Button export = new Button(this);
        export.setText("PC用スクリプトを書き出す");
        export.setTextSize(16);
        export.setFocusable(true);
        export.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exportScripts();
            }
        });
        root.addView(export);

        TextView info = new TextView(this);
        info.setTextSize(14);
        info.setPadding(0, dp(20), 0, 0);
        info.setText("PC側は初回だけ同梱スクリプトを管理者で実行してください。\n"
                + "以後はUSBを挿してアプリがONになれば、PCはDHCPで自動接続します。\n"
                + "PowerShell / Linux / FreeBSD 用は\n"
                + "「PC用スクリプトを書き出す」で /data/local/tmp に取り出せます。\n\n"
                + "rootサービス: " + (RootRelay.available() ? "OK" : "見つかりません"));
        root.addView(info);

        setContentView(scroll);
        toggle.requestFocus();
        RootRelay.run(RootRelay.acceptMobileData());
        refreshStatus();

        if (prefs.getBoolean(KEY_AUTO, true) && !prefs.getBoolean(KEY_MANUAL_OFF, false)) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    setUsb(true);
                }
            }, 1200);
        }
    }

    private int dp(int v) {
        return (int) (v * getResources().getDisplayMetrics().density + 0.5f);
    }

    private void exportScripts() {
        try {
            String dir = Ps1Exporter.exportAll(this);
            new AlertDialog.Builder(this)
                    .setTitle("PC用スクリプトを書き出しました")
                    .setMessage("スマホ内: " + dir + "\n"
                            + "pc-autoconnect.ps1\n"
                            + "pc-autoconnect.sh\n"
                            + "pc-autoconnect-linux.sh\n"
                            + "pc-autoconnect-freebsd.sh\n\n"
                            + "PC側で:\n"
                            + "adb pull " + dir + "pc-autoconnect.ps1 R:\\Projects\\Tethering-pc\\\n"
                            + "adb pull " + dir + "pc-autoconnect.sh R:\\Projects\\Tethering-pc\\\n"
                            + "adb pull " + dir + "pc-autoconnect-linux.sh R:\\Projects\\Tethering-pc\\\n"
                            + "adb pull " + dir + "pc-autoconnect-freebsd.sh R:\\Projects\\Tethering-pc\\")
                    .setPositiveButton("OK", null)
                    .show();
        } catch (Exception e) {
            Toast.makeText(this, "書き出し失敗: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void setUsb(boolean enable) {
        if (busy) {
            return;
        }
        busy = true;
        prefs.edit().putBoolean(KEY_MANUAL_OFF, !enable).apply();
        status.setText(enable ? "ON にしています..." : "OFF にしています...");

        StringBuilder cmd = new StringBuilder();
        if (enable) {
            cmd.append(RootRelay.acceptMobileData());
            // SoftBank's tetherAuthAPLNfp stops tethering again unless disabled.
            cmd.append("pm disable-user --user 0 jp.softbank.mb.tetherAuthNfp >/dev/null 2>&1\n");
            cmd.append("am force-stop jp.softbank.mb.tetherAuthNfp\n");
        }
        cmd.append("CLASSPATH=").append(getPackageCodePath())
                .append(" /system/bin/app_process /system/bin ")
                .append("jp.example.tethering.TetherCli usb ")
                .append(enable).append("\n");

        if (!RootRelay.run(cmd.toString())) {
            status.setText("rootサービスに書き込めません");
            busy = false;
            return;
        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                busy = false;
                refreshStatus();
            }
        }, 2500);
    }

    private void refreshStatus() {
        boolean on = isUsbTethered();
        lastOn = on;
        String ip = usbIp();
        android.util.Log.d("TetheringApp", "refreshStatus on=" + on + " ip=" + ip);
        toggle.setText(on ? "USBテザリングをOFF" : "USBテザリングをON");
        status.setText(on
                ? "USBテザリング: ON" + (ip != null ? "\n" + ip : "")
                : "USBテザリング: OFF");
        status.setTextColor(on ? Color.rgb(0, 128, 0) : Color.rgb(180, 0, 0));
    }

    private boolean isUsbTethered() {
        try {
            NetworkInterface ni = NetworkInterface.getByName("usb0");
            if (ni == null || !ni.isUp()) {
                return false;
            }
            for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                if (ia.getAddress() instanceof Inet4Address) {
                    return true;
                }
            }
        } catch (Exception ignored) {
        }
        return false;
    }

    private String usbIp() {
        try {
            NetworkInterface ni = NetworkInterface.getByName("usb0");
            if (ni == null) {
                return null;
            }
            for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                InetAddress a = ia.getAddress();
                if (a instanceof Inet4Address) {
                    return a.getHostAddress() + "/" + ia.getNetworkPrefixLength();
                }
            }
        } catch (Exception ignored) {
        }
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        handler.post(refresh);
    }

    @Override
    protected void onPause() {
        handler.removeCallbacks(refresh);
        super.onPause();
    }
}