commands) {
115 | return run(commands.toArray(new String[0]));
116 | }
117 |
118 | public synchronized static Result run(String... commands) {
119 | Shell.Result result = Shell.su(commands).exec();
120 | return new Result(result.getCode(), result.getOut());
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/app/src/main/java/moe/haruue/wadb/service/WadbTileService.java:
--------------------------------------------------------------------------------
1 | package moe.haruue.wadb.service;
2 |
3 | import android.content.Context;
4 | import android.graphics.drawable.Icon;
5 | import android.os.Build;
6 | import android.service.quicksettings.Tile;
7 | import android.service.quicksettings.TileService;
8 | import android.util.Log;
9 |
10 | import androidx.annotation.RequiresApi;
11 |
12 | import moe.haruue.wadb.R;
13 | import moe.haruue.wadb.WadbApplication;
14 | import moe.haruue.wadb.WadbPreferences;
15 | import moe.haruue.wadb.events.Events;
16 | import moe.haruue.wadb.events.GlobalRequestHandler;
17 | import moe.haruue.wadb.events.WadbStateChangedEvent;
18 | import moe.haruue.wadb.util.NetworksUtils;
19 |
20 | /**
21 | * @author Haruue Icymoon haruue@caoyue.com.cn
22 | */
23 |
24 | @RequiresApi(api = Build.VERSION_CODES.N)
25 | public abstract class WadbTileService extends TileService implements WadbStateChangedEvent {
26 |
27 | private static final String TAG = "WadbTileService";
28 |
29 | private final Runnable mStartWadbRunnable = () -> {
30 | GlobalRequestHandler.startWadb(WadbApplication.getWadbPort());
31 | };
32 |
33 | private static final Runnable STOP_WADB = GlobalRequestHandler::stopWadb;
34 |
35 | @Override
36 | public void onCreate() {
37 | super.onCreate();
38 | Events.registerAll(this);
39 | }
40 |
41 | @Override
42 | public void onDestroy() {
43 | super.onDestroy();
44 | Events.unregisterAll(this);
45 | }
46 |
47 | @Override
48 | public void onStartListening() {
49 | super.onStartListening();
50 |
51 | int port;
52 | if ((port = GlobalRequestHandler.getWadbPort()) != -1) {
53 | showStateOn(NetworksUtils.getLocalIPAddress(this), port);
54 | } else {
55 | showStateOff();
56 | }
57 | }
58 |
59 | @Override
60 | public void onClick() {
61 | super.onClick();
62 |
63 | Log.d(TAG, "onClick");
64 | boolean enableScreenLockSwitch = WadbApplication.getDefaultSharedPreferences().getBoolean(WadbPreferences.KEY_SCREEN_LOCK_SWITCH, false);
65 | if (getQsTile().getState() == Tile.STATE_ACTIVE) {
66 | if (enableScreenLockSwitch) {
67 | STOP_WADB.run();
68 | } else {
69 | unlockAndRun(STOP_WADB);
70 | }
71 | } else {
72 | if (enableScreenLockSwitch) {
73 | mStartWadbRunnable.run();
74 | } else {
75 | unlockAndRun(mStartWadbRunnable);
76 | }
77 | }
78 | }
79 |
80 | private void showStateOn(String ip, int port) {
81 | Log.d(TAG, "showStateOn");
82 |
83 | final Tile tile = getQsTile();
84 | final String address = ip + ":" + port;
85 | final Context context = this;
86 |
87 | tile.setState(Tile.STATE_ACTIVE);
88 | tile.setIcon(Icon.createWithResource(context, R.drawable.ic_qs_network_adb_on));
89 |
90 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
91 | tile.setLabel(context.getString(R.string.wireless_adb));
92 | tile.setSubtitle(address);
93 | } else {
94 | tile.setLabel(address);
95 | }
96 |
97 | tile.updateTile();
98 | }
99 |
100 | private void showStateOff() {
101 | Log.d(TAG, "showStateOff");
102 |
103 | final Tile tile = getQsTile();
104 | final Context context = this;
105 |
106 | tile.setState(Tile.STATE_INACTIVE);
107 | tile.setIcon(Icon.createWithResource(context, R.drawable.ic_qs_network_adb_off));
108 |
109 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
110 | tile.setLabel(context.getString(R.string.wireless_adb));
111 | tile.setSubtitle(context.getString(R.string.tile_off));
112 | } else {
113 | tile.setLabel(context.getString(R.string.wireless_adb));
114 | }
115 |
116 | tile.updateTile();
117 | }
118 |
119 | private void showStateUnavailable() {
120 | Tile tile = getQsTile();
121 | tile.setState(Tile.STATE_UNAVAILABLE);
122 | tile.updateTile();
123 | }
124 |
125 | @Override
126 | public void onWadbStarted(int port) {
127 | showStateOn(NetworksUtils.getLocalIPAddress(this), port);
128 | }
129 |
130 | @Override
131 | public void onWadbStopped() {
132 | showStateOff();
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
23 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
62 |
63 |
64 |
65 |
66 |
67 |
73 |
74 |
75 |
76 |
77 |
81 |
82 |
83 |
86 |
87 |
88 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/app/src/main/java/moe/haruue/wadb/util/NotificationHelper.kt:
--------------------------------------------------------------------------------
1 | package moe.haruue.wadb.util
2 |
3 | import android.app.Notification
4 | import android.app.NotificationChannel
5 | import android.app.NotificationManager
6 | import android.app.PendingIntent
7 | import android.content.ComponentName
8 | import android.content.Context
9 | import android.content.Intent
10 | import android.graphics.drawable.Icon
11 | import android.os.Build
12 | import androidx.annotation.RequiresApi
13 | import moe.haruue.wadb.R
14 | import moe.haruue.wadb.WadbApplication
15 | import moe.haruue.wadb.WadbPreferences
16 | import moe.haruue.wadb.component.HomeActivity
17 | import moe.haruue.wadb.receiver.TurnOffReceiver
18 |
19 | object NotificationHelper {
20 |
21 | private const val NOTIFICATION_ID = R.string.wireless_adb_short
22 | private const val NOTIFICATION_CHANNEL = "state"
23 |
24 | @JvmStatic
25 | fun showNotification(context: Context, ip: String, port: Int) {
26 | val notificationManager = context.getSystemService(NotificationManager::class.java) ?: return
27 | val contentPendingIntent = PendingIntent.getActivity(context, 0, Intent(context, HomeActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
28 | val turnOffIntent = Intent("moe.haruue.wadb.action.TURN_OFF_WADB").apply { component = ComponentName(context, TurnOffReceiver::class.java) }
29 |
30 | val turnOffPendingIntent = PendingIntent.getBroadcast(context, 0, turnOffIntent, PendingIntent.FLAG_IMMUTABLE)
31 | val turnOffAction = Notification.Action.Builder(Icon.createWithResource(context, R.drawable.ic_close_white_24dp), context.getString(R.string.notification_wadb_enabled_button_disable, context.getString(R.string.wireless_adb)), turnOffPendingIntent).build()
32 | val visibility = if (WadbApplication.defaultSharedPreferences.getBoolean(WadbPreferences.KEY_SCREEN_LOCK_SWITCH, false)) Notification.VISIBILITY_PUBLIC else Notification.VISIBILITY_PRIVATE
33 |
34 | // Android Q supports dark status bar, but still uses color restriction algorithm of light background,
35 | // so we still have to use light color here
36 | val color: Int = when (ThemeHelper.getTheme()) {
37 | ThemeHelper.THEME_GREEN -> {
38 | context.getColor(R.color.md_theme_green_palette_primary_50)
39 | }
40 | ThemeHelper.THEME_PINK -> {
41 | context.getColor(R.color.md_theme_pink_palette_primary_50)
42 | }
43 | else -> {
44 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
45 | context.getColor(android.R.color.system_accent1_500)
46 | } else {
47 | context.getColor(R.color.md_theme_green_palette_primary_50)
48 | }
49 | }
50 | }
51 |
52 | // Notification
53 | val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
54 | Notification.Builder(context, NOTIFICATION_CHANNEL)
55 | } else {
56 | @Suppress("DEPRECATION")
57 | Notification.Builder(context)
58 | }
59 |
60 | builder.setContentTitle(context.getString(R.string.notification_wadb_enabled_title, context.getString(R.string.wireless_adb)))
61 | .setContentText("$ip:$port")
62 | .setSmallIcon(R.drawable.ic_qs_network_adb_on)
63 | .setContentIntent(contentPendingIntent)
64 | .addAction(turnOffAction)
65 | .setVisibility(visibility)
66 | .setColor(color)
67 | .setOngoing(true)
68 |
69 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
70 | @Suppress("DEPRECATION")
71 | builder.setPriority(if (WadbApplication.defaultSharedPreferences.getBoolean(WadbPreferences.KEY_NOTIFICATION_LOW_PRIORITY, true)) Notification.PRIORITY_MIN else Notification.PRIORITY_DEFAULT)
72 | } else {
73 | createNotificationChannel(context)
74 | }
75 | notificationManager.notify(NOTIFICATION_ID, builder.build())
76 | }
77 |
78 | @JvmStatic
79 | fun cancelNotification(context: Context) {
80 | val notificationManager = context.getSystemService(NotificationManager::class.java)
81 | notificationManager?.cancel(NOTIFICATION_ID)
82 | }
83 |
84 | @RequiresApi(Build.VERSION_CODES.O)
85 | fun createNotificationChannel(context: Context) {
86 | val notificationManager = context.getSystemService(NotificationManager::class.java)
87 | if (notificationManager != null) {
88 | val channel = NotificationChannel(NOTIFICATION_CHANNEL, context.getString(R.string.notification_channel_state), NotificationManager.IMPORTANCE_DEFAULT)
89 | channel.setSound(null, null)
90 | channel.setShowBadge(false)
91 | channel.setBypassDnd(false)
92 | channel.enableLights(false)
93 | channel.enableVibration(false)
94 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
95 | channel.setAllowBubbles(false)
96 | }
97 | notificationManager.createNotificationChannel(channel)
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/moe/haruue/wadb/WadbApplication.kt:
--------------------------------------------------------------------------------
1 | package moe.haruue.wadb
2 |
3 | import android.app.Application
4 | import android.content.ComponentName
5 | import android.content.Context
6 | import android.content.SharedPreferences
7 | import android.content.pm.PackageManager
8 | import android.os.Build
9 | import android.os.Build.VERSION
10 | import moe.haruue.wadb.events.Events
11 | import moe.haruue.wadb.events.WadbFailureEvent
12 | import moe.haruue.wadb.events.WadbStateChangedEvent
13 | import moe.haruue.wadb.receiver.BootCompletedReceiver
14 | import moe.haruue.wadb.util.NetworksUtils
15 | import moe.haruue.wadb.util.NotificationHelper.cancelNotification
16 | import moe.haruue.wadb.util.NotificationHelper.showNotification
17 | import moe.haruue.wadb.util.ScreenKeeper
18 | import rikka.material.app.DayNightDelegate
19 | import rikka.sui.Sui
20 |
21 | lateinit var wadbApplication: WadbApplication
22 |
23 | class WadbApplication : Application(), WadbStateChangedEvent, WadbFailureEvent {
24 |
25 | companion object {
26 |
27 | val defaultSharedPreferenceName: String
28 | get() = BuildConfig.APPLICATION_ID + "_preferences"
29 |
30 | @JvmStatic
31 | val defaultSharedPreferences: SharedPreferences
32 | get() {
33 | var context: Context? = wadbApplication
34 | if (VERSION.SDK_INT >= Build.VERSION_CODES.N) {
35 | context = wadbApplication.createDeviceProtectedStorageContext()
36 | context.moveSharedPreferencesFrom(wadbApplication, defaultSharedPreferenceName)
37 | }
38 | return context!!.getSharedPreferences(defaultSharedPreferenceName, MODE_PRIVATE)
39 | }
40 |
41 | @JvmStatic
42 | val wadbPort: String
43 | get() {
44 | val port = defaultSharedPreferences.getString(WadbPreferences.KEY_WAKE_PORT, "5555")
45 | var p: Int
46 | try {
47 | p = port!!.toInt()
48 | if (p < 1025 || p > 65535) {
49 | p = 5555
50 | defaultSharedPreferences.edit().putString(WadbPreferences.KEY_WAKE_PORT, "5555").apply()
51 | }
52 | } catch (e: Throwable) {
53 | p = 5555
54 | defaultSharedPreferences.edit().putString(WadbPreferences.KEY_WAKE_PORT, "5555").apply()
55 | }
56 | return p.toString()
57 | }
58 |
59 | }
60 |
61 | override fun onCreate() {
62 | super.onCreate()
63 | Events.registerAll(this)
64 | DayNightDelegate.setApplicationContext(this)
65 | DayNightDelegate.setDefaultNightMode(DayNightDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
66 | }
67 |
68 | override fun onWadbStarted(port: Int) {
69 | val preferences = defaultSharedPreferences
70 | preferences.edit().putString(WadbPreferences.KEY_WAKE_PORT, Integer.toString(port)).apply()
71 | val ip = NetworksUtils.getLocalIPAddress(this)
72 | if (preferences.getBoolean(WadbPreferences.KEY_NOTIFICATION, true)) {
73 | showNotification(this, ip, port)
74 | }
75 | if (preferences.getBoolean(WadbPreferences.KEY_WAKE_LOCK, false)) {
76 | ScreenKeeper.acquireWakeLock(this)
77 | }
78 | }
79 |
80 | override fun onWadbStopped() {
81 | cancelNotification(this)
82 | ScreenKeeper.releaseWakeLock()
83 | }
84 |
85 | override fun attachBaseContext(base: Context) {
86 | super.attachBaseContext(base)
87 | wadbApplication = this
88 | Sui.init(base.packageName)
89 | }
90 |
91 | private inline val launcherActivity get() = ComponentName.createRelative(packageName, ".ui.activity.LaunchActivity")
92 |
93 | fun isLauncherActivityEnabled(): Boolean {
94 | val state = wadbApplication.packageManager.getComponentEnabledSetting(launcherActivity)
95 | return state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT || state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
96 | }
97 |
98 | fun disableLauncherActivity() {
99 | wadbApplication.packageManager.setComponentEnabledSetting(
100 | launcherActivity,
101 | PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
102 | PackageManager.DONT_KILL_APP
103 | )
104 | }
105 |
106 | fun enableLauncherActivity() {
107 | wadbApplication.packageManager.setComponentEnabledSetting(
108 | launcherActivity,
109 | PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
110 | PackageManager.DONT_KILL_APP
111 | )
112 | }
113 |
114 | private inline val bootCompletedReceiver get() = ComponentName.createRelative(packageName, BootCompletedReceiver::class.java.name)
115 |
116 | fun isBootCompletedReceiverEnabled(): Boolean {
117 | val state = wadbApplication.packageManager.getComponentEnabledSetting(bootCompletedReceiver)
118 | return state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
119 | }
120 |
121 | fun disableBootCompletedReceiver() {
122 | wadbApplication.packageManager.setComponentEnabledSetting(
123 | bootCompletedReceiver,
124 | PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
125 | PackageManager.DONT_KILL_APP
126 | )
127 | }
128 |
129 | fun enableBootCompletedReceiver() {
130 | wadbApplication.packageManager.setComponentEnabledSetting(
131 | bootCompletedReceiver,
132 | PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
133 | PackageManager.DONT_KILL_APP
134 | )
135 | }
136 | }
--------------------------------------------------------------------------------
/app/src/main/java/moe/haruue/wadb/component/HomeActivity.kt:
--------------------------------------------------------------------------------
1 | package moe.haruue.wadb.component
2 |
3 | import android.app.Dialog
4 | import android.content.Intent
5 | import android.content.pm.PackageManager
6 | import android.net.Uri
7 | import android.os.Build
8 | import android.os.Bundle
9 | import android.text.method.LinkMovementMethod
10 | import android.view.Menu
11 | import android.view.MenuItem
12 | import android.view.View
13 | import android.widget.ImageView
14 | import android.widget.TextView
15 | import androidx.core.view.isVisible
16 | import androidx.lifecycle.Lifecycle
17 | import com.google.android.material.dialog.MaterialAlertDialogBuilder
18 | import moe.haruue.wadb.BuildConfig
19 | import moe.haruue.wadb.R
20 | import moe.haruue.wadb.app.AppBarFragmentActivity
21 | import moe.haruue.wadb.util.ThemeHelper
22 | import rikka.core.ktx.unsafeLazy
23 | import rikka.html.text.HtmlCompat
24 | import rikka.html.text.toHtml
25 |
26 | class HomeActivity : AppBarFragmentActivity() {
27 |
28 | private val themes by unsafeLazy {
29 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S)
30 | arrayOf(
31 | getString(R.string.theme_default),
32 | getString(R.string.theme_pink),
33 | ) else
34 | arrayOf(
35 | getString(R.string.theme_default),
36 | getString(R.string.theme_green),
37 | getString(R.string.theme_pink),
38 | )
39 | }
40 |
41 | private val themesValue = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S)
42 | arrayOf(
43 | ThemeHelper.THEME_DEFAULT,
44 | ThemeHelper.THEME_PINK
45 | ) else
46 | arrayOf(
47 | ThemeHelper.THEME_DEFAULT,
48 | ThemeHelper.THEME_GREEN,
49 | ThemeHelper.THEME_PINK
50 | )
51 |
52 | private val themesId = themesValue.map { it.hashCode() }
53 |
54 | override fun onCreate(savedInstanceState: Bundle?) {
55 | super.onCreate(savedInstanceState)
56 |
57 | if (savedInstanceState == null) {
58 | val fragment = HomeFragment()
59 | supportFragmentManager.beginTransaction()
60 | .replace(R.id.fragment_container, fragment)
61 | .setMaxLifecycle(fragment, Lifecycle.State.RESUMED)
62 | .commit()
63 | }
64 | }
65 |
66 | override fun onCreateOptionsMenu(menu: Menu): Boolean {
67 | menuInflater.inflate(R.menu.home, menu)
68 | menu.findItem(R.id.menu_theme).subMenu.apply {
69 | val currentTheme = ThemeHelper.getTheme()
70 | for ((index, theme) in themes.withIndex()) {
71 | add(R.id.menu_theme_group, themesId[index].hashCode(), index, theme).apply {
72 | isCheckable = true
73 | isChecked = currentTheme == themesValue[index]
74 | }
75 | }
76 | setGroupCheckable(R.id.menu_theme_group, true, true)
77 | }
78 | return true
79 | }
80 |
81 | override fun onOptionsItemSelected(item: MenuItem): Boolean {
82 | return when (item.itemId) {
83 | R.id.menu_about -> {
84 | val context = this
85 | val versionName: String
86 | try {
87 | versionName = context.packageManager.getPackageInfo(context.packageName, 0).versionName
88 | } catch (ignored: PackageManager.NameNotFoundException) {
89 | return true
90 | }
91 | val text = StringBuilder()
92 | text.append(versionName)
93 | .append("")
94 | .append(
95 | getString(
96 | R.string.open_source_info,
97 | "GitHub",
98 | BuildConfig.LICENSE
99 | )
100 | )
101 | val translators = getString(R.string.translators)
102 | if (translators.isNotBlank()) {
103 | text.append("
").append(getString(R.string.translation_contributors, translators))
104 | }
105 | text.append("
").append(BuildConfig.COPYRIGHT)
106 |
107 | val dialog: Dialog = MaterialAlertDialogBuilder(context)
108 | .setView(R.layout.dialog_about)
109 | .show()
110 | (dialog.findViewById(R.id.design_about_icon) as ImageView).setImageDrawable(context.getDrawable(R.drawable.ic_launcher))
111 | (dialog.findViewById(R.id.design_about_title) as TextView).text =
112 | getString(R.string.wireless_adb_short)
113 | (dialog.findViewById(R.id.design_about_version) as TextView).apply {
114 | movementMethod = LinkMovementMethod.getInstance()
115 | this.text = text.toHtml(HtmlCompat.FROM_HTML_OPTION_TRIM_WHITESPACE)
116 | }
117 | (dialog.findViewById(R.id.design_about_info) as TextView).isVisible = false
118 | true
119 | }
120 | R.id.menu_translate -> {
121 | startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.TRANSLATION_URL)))
122 | true
123 | }
124 | else -> {
125 | val index = themesId.indexOf(item.itemId)
126 | if (index == -1) return super.onOptionsItemSelected(item)
127 |
128 | if (ThemeHelper.getTheme() != themesValue[index]) {
129 | ThemeHelper.setLightTheme(themesValue[index])
130 | recreate()
131 | }
132 | return true
133 | }
134 | }
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/app/src/main/java/moe/haruue/wadb/events/GlobalRequestHandler.java:
--------------------------------------------------------------------------------
1 | package moe.haruue.wadb.events;
2 |
3 | import android.os.SystemProperties;
4 | import android.text.TextUtils;
5 | import android.util.Log;
6 |
7 | import java.util.Arrays;
8 | import java.util.concurrent.ExecutorService;
9 | import java.util.concurrent.Executors;
10 |
11 | import moe.haruue.wadb.BuildConfig;
12 | import moe.haruue.wadb.util.SuShell;
13 | import rikka.shizuku.Shizuku;
14 | import rikka.shizuku.ShizukuSystemProperties;
15 | import rikka.sui.Sui;
16 |
17 | import static android.content.pm.PackageManager.PERMISSION_GRANTED;
18 |
19 | public class GlobalRequestHandler {
20 |
21 | private static final String TAG = "GlobalRequestHandler";
22 | private static final boolean DEBUG = BuildConfig.DEBUG;
23 |
24 | private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(1);
25 |
26 | private final static String[] STOP_WADB_COMMANDS;
27 |
28 | static {
29 | if (BuildConfig.DONOT_RESTART_ADBD && BuildConfig.DEBUG) {
30 | STOP_WADB_COMMANDS = new String[]{
31 | "setprop service.adb.tcp.port -1"
32 | };
33 | } else {
34 | STOP_WADB_COMMANDS = new String[]{
35 | "setprop service.adb.tcp.port -1",
36 | "setprop ctl.restart adbd"
37 | };
38 | }
39 | }
40 |
41 | private static String[] getStartWadbCommand(String port) {
42 | if (BuildConfig.DONOT_RESTART_ADBD && BuildConfig.DEBUG) {
43 | return new String[]{
44 | "setprop service.adb.tcp.port " + port
45 | };
46 | } else {
47 | return new String[]{
48 | "setprop service.adb.tcp.port " + port,
49 | "setprop ctl.restart adbd"
50 | };
51 | }
52 | }
53 |
54 | public static int getWadbPort() {
55 | String port = SystemProperties.get("service.adb.tcp.port");
56 | if (!TextUtils.isEmpty(port)) {
57 | try {
58 | return Integer.parseInt(port);
59 | } catch (Throwable tr) {
60 | tr.printStackTrace();
61 | }
62 | }
63 | return -1;
64 | }
65 |
66 | public static void checkWadbState() {
67 | Log.d(TAG, "checkWadbState");
68 |
69 | int port;
70 | if ((port = getWadbPort()) != -1) {
71 | Events.postWadbStateChangedEvent(event -> event.onWadbStarted(port));
72 | } else {
73 | Events.postWadbFailureEvent(WadbFailureEvent::onOperateFailure);
74 | }
75 | }
76 |
77 | private static int runCommands(String[] cmds) {
78 | Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
79 |
80 | int exitCode = -1;
81 | long time = 0;
82 | if (DEBUG) {
83 | time = System.currentTimeMillis();
84 | }
85 |
86 | if (!SuShell.available()) {
87 | Events.postWadbFailureEvent(WadbFailureEvent::onRootPermissionFailure);
88 | return exitCode;
89 | }
90 | SuShell.Result shellResult = SuShell.run(cmds);
91 | exitCode = shellResult.exitCode;
92 | if (DEBUG) {
93 | Log.d(TAG, "su " + Arrays.toString(cmds) + " takes " + (System.currentTimeMillis() - time) + "ms");
94 | }
95 | return exitCode;
96 | }
97 |
98 | public static void startWadb(String port) {
99 | if (Sui.isSui()) {
100 | Runnable runnable = () -> {
101 | try {
102 | ShizukuSystemProperties.set("service.adb.tcp.port", port);
103 | if (!BuildConfig.DONOT_RESTART_ADBD || !BuildConfig.DEBUG) {
104 | ShizukuSystemProperties.set("ctl.restart", "adbd");
105 | }
106 | Events.postWadbStateChangedEvent(event -> event.onWadbStarted(Integer.parseInt(port)));
107 | } catch (Throwable e) {
108 | e.printStackTrace();
109 | Events.postWadbFailureEvent(WadbFailureEvent::onOperateFailure);
110 | }
111 | };
112 |
113 | if (Shizuku.checkSelfPermission() == PERMISSION_GRANTED) {
114 | runnable.run();
115 | } else if (Shizuku.shouldShowRequestPermissionRationale()) {
116 | Events.postWadbFailureEvent(WadbFailureEvent::onRootPermissionFailure);
117 | } else {
118 | Shizuku.addRequestPermissionResultListener(new Shizuku.OnRequestPermissionResultListener() {
119 | @Override
120 | public void onRequestPermissionResult(int requestCode, int grantResult) {
121 | if (requestCode != 1) return;
122 |
123 | Shizuku.removeRequestPermissionResultListener(this);
124 | if (grantResult == PERMISSION_GRANTED) {
125 | runnable.run();
126 | }
127 | }
128 | });
129 | Shizuku.requestPermission(1);
130 | }
131 | } else {
132 | EXECUTOR.submit(() -> {
133 | int exitCode = runCommands(getStartWadbCommand(port));
134 | Log.d(TAG, "startWadb: " + exitCode);
135 | if (exitCode == 0) {
136 | Events.postWadbStateChangedEvent(event -> event.onWadbStarted(Integer.parseInt(port)));
137 | } else {
138 | Events.postWadbFailureEvent(WadbFailureEvent::onOperateFailure);
139 | }
140 | });
141 | }
142 | }
143 |
144 | public static void stopWadb() {
145 | if (Sui.isSui()) {
146 | Runnable runnable = () -> {
147 | try {
148 | ShizukuSystemProperties.set("service.adb.tcp.port", "-1");
149 | if (!BuildConfig.DONOT_RESTART_ADBD || !BuildConfig.DEBUG) {
150 | ShizukuSystemProperties.set("ctl.restart", "adbd");
151 | }
152 | Events.postWadbStateChangedEvent(WadbStateChangedEvent::onWadbStopped);
153 | } catch (Throwable e) {
154 | e.printStackTrace();
155 | Events.postWadbFailureEvent(WadbFailureEvent::onOperateFailure);
156 | }
157 | };
158 |
159 | if (Shizuku.checkSelfPermission() == PERMISSION_GRANTED) {
160 | runnable.run();
161 | } else if (Shizuku.shouldShowRequestPermissionRationale()) {
162 | Events.postWadbFailureEvent(WadbFailureEvent::onRootPermissionFailure);
163 | } else {
164 | Shizuku.addRequestPermissionResultListener(new Shizuku.OnRequestPermissionResultListener() {
165 | @Override
166 | public void onRequestPermissionResult(int requestCode, int grantResult) {
167 | if (requestCode != 2) return;
168 |
169 | Shizuku.removeRequestPermissionResultListener(this);
170 | if (grantResult == PERMISSION_GRANTED) {
171 | runnable.run();
172 | }
173 | }
174 | });
175 | Shizuku.requestPermission(2);
176 | }
177 | } else {
178 | EXECUTOR.submit(() -> {
179 | int exitCode = runCommands(STOP_WADB_COMMANDS);
180 |
181 | if (exitCode == 0) {
182 | Events.postWadbStateChangedEvent(WadbStateChangedEvent::onWadbStopped);
183 | } else {
184 | Events.postWadbFailureEvent(WadbFailureEvent::onOperateFailure);
185 | }
186 | });
187 | }
188 | }
189 | }
190 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | import java.nio.file.Paths
2 |
3 | plugins {
4 | id('com.android.application')
5 | id('kotlin-android')
6 | id('dev.rikka.tools.autoresconfig')
7 | id('dev.rikka.tools.materialthemebuilder')
8 | }
9 |
10 | def localFile = rootProject.file('local.properties')
11 | def localProps = new Properties()
12 | def dontRestartAdbd
13 | if (localFile.canRead()) {
14 | localProps.load(localFile.newDataInputStream())
15 | dontRestartAdbd = localProps.get("debug.dontRestartAdbd", false)
16 | }
17 |
18 | def signFile = rootProject.file('signing.properties')
19 | def signProps = new Properties()
20 | def hasSignConfig = false
21 | if (signFile.canRead()) {
22 | signProps.load(new FileInputStream(signFile))
23 | hasSignConfig = true
24 | }
25 |
26 | android {
27 | compileSdkVersion target_sdk
28 | ndkVersion "23.1.7779620"
29 | defaultConfig {
30 | applicationId "moe.haruue.wadb"
31 | minSdkVersion min_sdk
32 | targetSdkVersion target_sdk
33 | versionCode rootProject.ext.versionCode
34 | versionName rootProject.ext.versionName
35 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
36 | resConfigs 'de', 'id', 'it', 'ja', 'pt-rBR', 'ru', 'tr', 'zh-rCN', 'zh-rTW'
37 | buildConfigField "String", "GITHUB_URL", "\"https://github.com/RikkaApps/WADB\""
38 | buildConfigField "String", "LICENSE", "\"Apache License 2.0\""
39 | buildConfigField "String", "TRANSLATION_URL", "\"https://rikka.app/contribute_translation/\""
40 | buildConfigField "String", "COPYRIGHT", "\"Copyright © Haruue Icymoon, PinkD, Rikka\""
41 | buildConfigField "boolean", "DONOT_RESTART_ADBD", "${dontRestartAdbd}" // set it true to prevent restart adbd (for debugging)
42 | setProperty("archivesBaseName", "wadb-v${versionName}")
43 | externalNativeBuild {
44 | cmake {
45 | abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
46 | arguments '-DANDROID_STL=none'
47 | }
48 | }
49 | }
50 | buildFeatures {
51 | prefab = true
52 | }
53 | signingConfigs {
54 | if (hasSignConfig) {
55 | sign {
56 | storeFile signProps.getProperty("KEYSTORE_FILE") != null ? file(signProps.getProperty("KEYSTORE_FILE")) : android.signingConfigs.debug.storeFile
57 | storePassword signProps.getProperty("KEYSTORE_PASSWORD", android.signingConfigs.debug.storePassword)
58 | keyAlias signProps.getProperty("KEYSTORE_ALIAS", android.signingConfigs.debug.keyAlias)
59 | keyPassword signProps.getProperty("KEYSTORE_ALIAS_PASSWORD", android.signingConfigs.debug.keyPassword)
60 | }
61 | }
62 | }
63 | compileOptions {
64 | sourceCompatibility JavaVersion.VERSION_1_8
65 | targetCompatibility JavaVersion.VERSION_1_8
66 | }
67 | kotlinOptions {
68 | jvmTarget = "1.8"
69 | }
70 | buildTypes {
71 | debug {
72 | if (hasSignConfig) {
73 | signingConfig signingConfigs.sign
74 | }
75 | }
76 | release {
77 | minifyEnabled true
78 | shrinkResources true
79 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
80 | if (hasSignConfig) {
81 | signingConfig signingConfigs.sign
82 | }
83 | }
84 | }
85 | externalNativeBuild {
86 | cmake {
87 | path "src/main/cpp/CMakeLists.txt"
88 | }
89 | }
90 | packagingOptions {
91 | jniLibs {
92 | excludes += ['/kotlin/**']
93 | }
94 | resources {
95 | excludes += ['/META-INF/*.version', '/META-INF/*.version', '/META-INF/*.kotlin_module', '/kotlin/**']
96 | }
97 | }
98 | dependenciesInfo.includeInApk false
99 | lint {
100 | checkReleaseBuilds false
101 | }
102 | }
103 |
104 | autoResConfig {
105 | generateClass = false
106 | generateRes = false
107 | }
108 |
109 | materialThemeBuilder {
110 | themes {
111 | wadb {
112 | primaryColor = "#88b984"
113 | dynamicColors = true
114 | lightThemeFormat = "Theme.Material3.Light.%s"
115 | lightThemeParent = "Theme.Material3.Light.Rikka"
116 | darkThemeFormat = "Theme.Material3.Dark.%s"
117 | darkThemeParent = "Theme.Material3.Dark.Rikka"
118 | }
119 | green {
120 | primaryColor = "#88b984"
121 | lightThemeFormat = "ThemeOverlay.%s.Light"
122 | lightThemeParent = "ThemeOverlay"
123 | darkThemeFormat = "ThemeOverlay.%s.Dark"
124 | darkThemeParent = "ThemeOverlay"
125 | }
126 | pink {
127 | primaryColor = "#F5A9B8"
128 | lightThemeFormat = "ThemeOverlay.%s.Light"
129 | lightThemeParent = "ThemeOverlay"
130 | darkThemeFormat = "ThemeOverlay.%s.Dark"
131 | darkThemeParent = "ThemeOverlay"
132 | }
133 | }
134 | generatePalette = true
135 | packageName = "moe.haruue.wadb"
136 | }
137 |
138 | def optimizeReleaseResources = task('optimizeReleaseResources').doLast {
139 | def aapt2 = Paths.get(project.android.sdkDirectory.path, 'build-tools', project.android.buildToolsVersion, 'aapt2')
140 | def zip = Paths.get(project.buildDir.path, 'intermediates',
141 | 'processed_res', 'release', 'out', "resources-release.ap_")
142 | def optimized = new File("${zip}.opt")
143 | def cmd = exec {
144 | commandLine aapt2, 'optimize', '--collapse-resource-names',
145 | '--shorten-resource-paths',
146 | '-o', optimized, zip
147 | ignoreExitValue false
148 | }
149 | if (cmd.exitValue == 0) {
150 | delete(zip)
151 | optimized.renameTo("$zip")
152 | }
153 | }
154 |
155 | tasks.whenTaskAdded { task ->
156 | if (task.name == 'processReleaseResources') {
157 | task.finalizedBy optimizeReleaseResources
158 | }
159 | }
160 |
161 | android.applicationVariants.all { variant ->
162 | variant.outputs.all {
163 | if (variant.getBuildType().isMinifyEnabled()) {
164 | variant.assembleProvider.get().doLast {
165 | copy {
166 | from variant.mappingFile
167 | into "release"
168 | rename { String fileName ->
169 | "mapping-${variant.versionCode}.txt"
170 | }
171 | }
172 | copy {
173 | from outputFile
174 | into "release"
175 | }
176 | }
177 | }
178 | }
179 | }
180 |
181 | repositories {
182 | maven {
183 | url 'https://jitpack.io'
184 | content {
185 | includeGroup("com.github.topjohnwu.libsu")
186 | }
187 | }
188 | }
189 |
190 | configurations.all {
191 | exclude group: 'androidx.appcompat', module: 'appcompat'
192 | }
193 |
194 | dependencies {
195 | compileOnly project(':hidden')
196 |
197 | implementation 'com.google.android.material:material:1.7.0-alpha02'
198 | implementation 'androidx.core:core-ktx:1.8.0'
199 | implementation 'androidx.fragment:fragment-ktx:1.4.1'
200 | implementation 'androidx.recyclerview:recyclerview:1.2.1'
201 | implementation 'androidx.preference:preference-ktx:1.2.0'
202 |
203 | implementation "dev.rikka.rikkax.appcompat:appcompat:1.4.1"
204 | implementation "dev.rikka.rikkax.core:core:1.4.0"
205 | implementation 'dev.rikka.rikkax.html:html-ktx:1.1.2'
206 | implementation 'dev.rikka.rikkax.material:material:2.4.0'
207 | implementation 'dev.rikka.rikkax.material:material-preference:1.1.0'
208 | implementation 'dev.rikka.rikkax.recyclerview:recyclerview-ktx:1.3.1'
209 | implementation 'dev.rikka.rikkax.widget:borderview:1.1.0'
210 | implementation 'dev.rikka.rikkax.widget:mainswitchbar:1.1.0'
211 | implementation 'dev.rikka.ndk.thirdparty:cxx:1.2.0'
212 |
213 | def libsuVersion = '4.0.3'
214 | implementation "com.github.topjohnwu.libsu:core:${libsuVersion}"
215 |
216 | def shizuku_version = '12.0.0'
217 | implementation "dev.rikka.shizuku:api:${shizuku_version}"
218 | }
219 |
--------------------------------------------------------------------------------
/app/src/main/cpp/netlink.cpp:
--------------------------------------------------------------------------------
1 | #include "netlink.h"
2 |
3 | #include