Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion android/assets/i18n/java-ar.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-en.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-es.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-fr.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-id.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-ja.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-ko.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-ru.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-zh-Hant.json

Large diffs are not rendered by default.

60 changes: 59 additions & 1 deletion android/java/cc/codroid/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,61 @@ private boolean fromUs(Intent i) {
static final String ACTION_SHIZUKU_NOOP = "cc.codroid.SHIZUKU_NOOP";
/** 主界面(聊天)在前台吗:通知只在用户没盯着聊天时发 */
static volatile boolean visible;
private static volatile java.lang.ref.WeakReference<MainActivity> foregroundOwner;

private static final SplitPairing splitPairing = new SplitPairing();

static void clearSplitPairing(Context context) {
new Handler(Looper.getMainLooper()).post(() -> {
splitPairing.reset();
SplitPairingNotice.dismiss(context);
});
}

static org.json.JSONObject splitPairingStatus() throws org.json.JSONException {
SplitPairing.Result r=splitPairing.snapshot();
return new org.json.JSONObject().put("supported",SplitPairing.supported(Build.VERSION.SDK_INT))
.put("sdk",Build.VERSION.SDK_INT).put("phase",r.phase).put("path",r.path).put("message",Tr.t(r.message()));
}

/** Socket worker delegates to the actual foreground Activity; no background task launch. */
static org.json.JSONObject requestSplitPairing() throws Exception {
if(!SplitPairing.supported(Build.VERSION.SDK_INT))
return splitPairingStatus().put("ok",false).put("message",Tr.t("此 Android 版本不支持分屏。"));
MainActivity a=foregroundOwner==null?null:foregroundOwner.get();
if(a==null||!visible||a.isFinishing()||a.isDestroyed())
return splitPairingStatus().put("ok",false).put("message",Tr.t("请先回到 cccodroid 前台,再尝试分屏打开设置。"));
java.util.concurrent.FutureTask<SplitPairing.Result> work=new java.util.concurrent.FutureTask<>(()->splitPairing.start(new SplitPairing.Host(){
public int sdk(){return Build.VERSION.SDK_INT;}
public boolean foreground(){return visible&&!a.isFinishing()&&!a.isDestroyed()&&a.hasWindowFocus()&&!guarding()&&"pairing".equals(ShizukuSetup.get(a).phase);}
public boolean visibleInMultiWindow(){return !a.isFinishing()&&!a.isDestroyed()&&visible&&a.isInMultiWindowMode();}
public void openAdjacent(){
SplitPairingNotice.dismiss(a);
Intent target=new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
Bundle args=new Bundle();args.putString(":settings:fragment_args_key","toggle_adb_wireless");
target.putExtra(":settings:fragment_args_key","toggle_adb_wireless");
target.putExtra(":settings:show_fragment_args",args);
target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
a.startActivity(target);
}
public void later(Runnable task,int delay){new Handler(Looper.getMainLooper()).postDelayed(task,delay);}
public void showManualHint(){
SplitPairing.Result result=splitPairing.snapshot();
String message=Tr.t(result.message());
android.widget.Toast.makeText(a.getApplicationContext(),message,android.widget.Toast.LENGTH_LONG).show();
SplitPairingNotice.show(a,message,()->splitPairing.snapshot()==result);
}
}));
a.ui.post(work);
try {
SplitPairing.Result r=work.get(3,java.util.concurrent.TimeUnit.SECONDS);
return splitPairingStatus().put("ok",r.ok()).put("message",Tr.t(r.message()));
}catch(Exception e){
work.cancel(false);
return splitPairingStatus().put("ok",false).put("message",Tr.t("分屏请求未完成,请回到应用后重试。"));
}
}

/** 本应用有界面在前台吗(主界面或独立浏览器):静默更新、读剪贴板这类按「用户在不在用本应用」判断(11-04 报告 A4) */
static boolean appForeground() { return visible || BrowserActivity.visible; }

Expand Down Expand Up @@ -346,7 +401,7 @@ private boolean mainInputReady(android.webkit.WebView w) {
@Override public void run() { FrameRate.apply(MainActivity.this); ui.postDelayed(this, 30000); }
};

@Override protected void onResume() { super.onResume(); visible = true; applyLandBars(); Battery.foreground(true); FrameRate.apply(this);
@Override protected void onResume() { super.onResume(); foregroundOwner = new java.lang.ref.WeakReference<>(this); visible = true; applyLandBars(); Battery.foreground(true); FrameRate.apply(this);
// 在后台从常驻通知点了「停止」、界面还活着:回来时把网关服务拉起来(审查 #105 06-007)。以前只有 boot 起服务,回来只能对着连不上的页面
if (booted && !GatewayService.serviceUp()) GatewayService.start(this);
Consent.runNext(this); // 上次排着的锁屏签名(界面当时正在关、没问成)
Expand All @@ -362,6 +417,7 @@ private boolean mainInputReady(android.webkit.WebView w) {
if (!isInMultiWindowMode()) { visible = false; Notify.get(this).onBackground(); } }
@Override protected void onStop() {
super.onStop();
if (foregroundOwner != null && foregroundOwner.get() == this) foregroundOwner = null;
// 分屏里被整个切走 / 熄屏时 onPause 没记过账,这里补上;转屏重建不算到后台
boolean was = visible;
visible = false;
Expand Down Expand Up @@ -414,6 +470,7 @@ private void applyLandBars() {
}
@Override public void onMultiWindowModeChanged(boolean on, android.content.res.Configuration cfg) {
super.onMultiWindowModeChanged(on, cfg);
if (on && splitPairing.multiWindowDetected()) SplitPairingNotice.dismiss(this);
applyLandBars();
}
/** 壁纸主色(安卓 12+ 的动态取色,系统 system_accent1_500);更早的系统没有,返回空串。
Expand Down Expand Up @@ -594,6 +651,7 @@ else if (ACTION_UPDATE.equals(a)) {
if (r != null && !r.optBoolean("ok", true) && !msg.isEmpty())
android.widget.Toast.makeText(this, msg, android.widget.Toast.LENGTH_LONG).show();
}
else if (SplitPairingNotice.ACTION_ACK.equals(a)) SplitPairingNotice.dismiss(this);
else if (ACTION_SHIZUKU.equals(a)) ShizukuSetup.get(this).activate();
else if (ACTION_FACTORY_RESET.equals(a)) askFactoryReset();
else if (ACTION_A11Y_OK.equals(a)) confirmA11y(i.getStringExtra("mode"), i.getBooleanExtra("on", false));
Expand Down
1 change: 1 addition & 0 deletions android/java/cc/codroid/Priv.java
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ private static void handle(LocalSocket s) {
}
ShizukuSetup.get(ctx).activate(); resp = status(); break;
}
case "shz_split_settings": resp = MainActivity.requestSplitPairing(); break;
case "shz_pair": ShizukuSetup.get(ctx).onCode(req.optString("code")); resp = status(); break;
case "shz_repair": ShizukuSetup.get(ctx).repair(); resp = status(); break;
case "shz_autostart": {
Expand Down
12 changes: 9 additions & 3 deletions android/java/cc/codroid/ShizukuSetup.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,15 @@ final class ShizukuSetup {
private ShizukuSetup(Context c) {
ctx = c;
env = new Env(c);
ensureNotificationChannel(c);
flushStaleNote(c);
new Thread(this::sweepLegacyAdb, "shz-sweep").start();
}

static void ensureNotificationChannel(Context c) {
NotificationChannel ch = new NotificationChannel(CH, Tr.t("Shizuku 激活"), NotificationManager.IMPORTANCE_HIGH);
ch.setDescription(Tr.t("无线调试配对码输入框、激活结果"));
c.getSystemService(NotificationManager.class).createNotificationChannel(ch);
flushStaleNote(c);
new Thread(this::sweepLegacyAdb, "shz-sweep").start();
}

/**
Expand Down Expand Up @@ -143,7 +147,7 @@ private void flushStaleNote(Context c) {
private static final String EXTRA_PROGRESS = "cc.codroid.progress";

/** 用户退出应用:收起配对 / 激活通知并注销 NSD 配对监听,避免后台泄漏 */
void onExit() { stopPairDiscovery(); cancelNote(); }
void onExit() { stopPairDiscovery(); cancelNote(); MainActivity.clearSplitPairing(ctx); }

SharedPreferences prefs() { return ctx.getSharedPreferences("shz", Context.MODE_PRIVATE); }
boolean hasWss() { return ctx.checkSelfPermission(WSS) == PackageManager.PERMISSION_GRANTED; }
Expand All @@ -153,6 +157,7 @@ void put(JSONObject o) throws Exception {
synchronized (ring) { lg = new JSONArray(ring); }
o.put("setup", new JSONObject().put("phase", phase).put("message", message).put("done", done).put("total", total).put("log", lg));
o.put("autostart", autostart());
o.put("splitPairing", MainActivity.splitPairingStatus());
o.put("paired", prefs().getBoolean("paired", false));
o.put("pairOk", pairOk);
if (Priv.running()) verifyPairAsync();
Expand All @@ -167,6 +172,7 @@ void put(JSONObject o) throws Exception {
}

private void set(String p, String m) {
if (phase.equals("pairing") && !p.equals("pairing")) MainActivity.clearSplitPairing(ctx);
phase = p; message = m == null ? "" : m;
log(p + " " + message);
}
Expand Down
71 changes: 71 additions & 0 deletions android/java/cc/codroid/SplitPairing.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package cc.codroid;

/** User-requested adjacent Settings launch. One public Intent API has different version semantics. */
final class SplitPairing {
static final int MIN_SDK = 24;
static final int FULLSCREEN_SDK = 32;
static final int CHECK_MS = 250;
static final int CHECKS = 10;
interface Host {
int sdk();
boolean foreground();
boolean visibleInMultiWindow();
void openAdjacent() throws Exception;
void later(Runnable work, int delayMs);
void showManualHint();
}
static final class Result {
final String phase, path;
Result(String phase, String path) { this.phase=phase; this.path=path; }
boolean ok() { return !"unsupported".equals(phase)&&!"foreground".equals(phase); }
String message() {
switch (phase) {
case "opening": return "正在尝试分屏打开设置…";
case "multiwindow": return "已检测到多窗口。请在另一窗口进入无线调试,打开配对码弹框后,在这里填写配对码和端口。";
case "manual": return "尚未检测到分屏。请在最近任务中将 cccodroid 与系统设置设为分屏,再打开无线调试的配对码弹框。配对完成前请保持两个窗口打开。";
case "foreground": return "请先回到 cccodroid 前台,再尝试分屏打开设置。";
case "unsupported": return "此 Android 版本不支持分屏。";
default: return "";
}
}
}
private volatile Result result = new Result("idle", "");
private long generation;
static boolean supported(int sdk) { return sdk>=MIN_SDK; }
Result snapshot() { return result; }
void reset() {
generation++;
result = new Result("idle", "");
}
// A late framework confirmation supersedes the timeout observation and any queued notice.
boolean multiWindowDetected() {
if (!"opening".equals(result.phase) && !"manual".equals(result.phase)) return false;
generation++;
result = new Result("multiwindow", result.path);
return true;
}
// Called on the UI thread. Querying this result never launches an Activity.
Result start(Host host) {
if(!supported(host.sdk()))return new Result("unsupported","");
if(!host.foreground())return new Result("foreground","");
if("opening".equals(result.phase))return result;
String path=host.sdk()>=FULLSCREEN_SDK&&!host.visibleInMultiWindow()?"fullscreen":"adjacent";
long request=++generation;
result=new Result("opening",path);
try { host.openAdjacent(); }
catch(Exception e) { return manual(host,path); }
host.later(()->check(host,request,path,CHECKS),CHECK_MS);
return result;
}
private void check(Host host,long request,String path,int remaining) {
if(request!=generation)return;
if(host.visibleInMultiWindow()) { result=new Result("multiwindow",path);return; }
if(remaining<=1) { manual(host,path);return; }
host.later(()->check(host,request,path,remaining-1),CHECK_MS);
}
private Result manual(Host host,String path) {
result=new Result("manual",path);
host.showManualHint();
return result;
}
}
68 changes: 68 additions & 0 deletions android/java/cc/codroid/SplitPairingNotice.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package cc.codroid;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.BooleanSupplier;

/** Acknowledgeable reminder visible while the user is in system Settings. */
final class SplitPairingNotice {
static final String ACTION_ACK = "cc.codroid.SPLIT_PAIRING_ACK";
private static final String TAG = "split-pairing";
private static final int ID = 1;
private static final ExecutorService worker = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "split-pairing-notice"); t.setDaemon(true); return t;
});

static void show(Context c, String message, BooleanSupplier stillNeeded) {
Context app = c.getApplicationContext();
worker.execute(() -> {
try {
if (!stillNeeded.getAsBoolean()) return;
NotificationManager nm = app.getSystemService(NotificationManager.class);
if (!nm.areNotificationsEnabled()) {
android.util.Log.w("cccodroid", "分屏提醒通知未开启;保留页面手动指引");
return;
}
// Use the same channel the user already sees for pairing-code input on MIUI.
// Do not call ShizukuSetup.get(): notification setup must not start activation / ADB.
ShizukuSetup.ensureNotificationChannel(app);
PendingIntent acknowledge = PendingIntent.getActivity(app, 5301,
MainActivity.internal(app, ACTION_ACK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
// Match the pairing prompt: persistent heads-up while Settings is in front.
// The fullscreen fallback is a no-op, not ACK or activation; only a user tap acknowledges.
PendingIntent attention = PendingIntent.getActivity(app, 5302,
MainActivity.internal(app, MainActivity.ACTION_SHIZUKU_NOOP).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
Notification notice = new Notification.Builder(app, ShizukuSetup.CH)
.setSmallIcon(android.R.drawable.ic_secure)
.setContentTitle(Tr.t("未检测到分屏,请手动操作"))
.setContentText(message)
.setStyle(new Notification.BigTextStyle().bigText(message))
.setContentIntent(acknowledge)
.addAction(new Notification.Action.Builder(null, Tr.t("知道了,返回应用"), acknowledge).build())
.setCategory(Notification.CATEGORY_REMINDER)
.setFullScreenIntent(attention, true)
.setOnlyAlertOnce(false).setOngoing(true).setAutoCancel(true)
.setTimeoutAfter(600_000).build();
if (stillNeeded.getAsBoolean()) nm.notify(TAG, ID, notice);
} catch (RuntimeException e) {
android.util.Log.w("cccodroid", "无法显示分屏提醒;保留页面手动指引", e);
}
});
}

static void dismiss(Context c) {
Context app = c.getApplicationContext();
worker.execute(() -> {
try { app.getSystemService(NotificationManager.class).cancel(TAG, ID); }
catch (RuntimeException e) { android.util.Log.w("cccodroid", "无法收起分屏提醒", e); }
});
}
}
51 changes: 51 additions & 0 deletions android/tests/cc/codroid/SplitPairingTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package cc.codroid;
import java.util.ArrayDeque;
final class SplitPairingTest {
static int checks;
static void check(boolean value){if(!value)throw new AssertionError("check "+checks);checks++;}
static final class Fake implements SplitPairing.Host {
int sdk=32,opens,hints;
boolean front=true,multi,visible=true,fail;
ArrayDeque<Runnable> pending=new ArrayDeque<>();
public int sdk(){return sdk;}
public boolean foreground(){return front;}
public boolean visibleInMultiWindow(){return multi&&visible;}
public void openAdjacent()throws Exception {opens++;if(fail)throw new Exception("blocked");}
public void later(Runnable task,int delay){check(delay==250);pending.add(task);}
public void showManualHint(){hints++;}
void tick(){pending.remove().run();}
void finish(){while(!pending.isEmpty())tick();}
}
public static void main(String[] args){
SplitPairing p=new SplitPairing();Fake h=new Fake();h.sdk=23;
check(!SplitPairing.supported(23));check(SplitPairing.supported(24));
check(!p.start(h).ok());check(h.opens==0&&h.pending.isEmpty());
h.sdk=24;check(p.start(h).path.equals("adjacent"));h.multi=true;h.finish();
check(p.snapshot().phase.equals("multiwindow"));check(h.opens==1&&h.hints==0);
p=new SplitPairing();h=new Fake();h.sdk=31;p.start(h);h.finish();
check(h.opens==1&&h.hints==1);check(p.snapshot().phase.equals("manual"));
p=new SplitPairing();h=new Fake();check(p.start(h).path.equals("fullscreen"));
check(p.start(h).phase.equals("opening"));check(h.opens==1);
h.tick();h.multi=true;h.finish();check(p.snapshot().phase.equals("multiwindow"));
check(h.hints==0);
p=new SplitPairing();h=new Fake();h.multi=true;check(p.start(h).path.equals("adjacent"));h.finish();
check(h.opens==1&&p.snapshot().phase.equals("multiwindow"));
p=new SplitPairing();h=new Fake();h.front=false;check(p.start(h).phase.equals("foreground"));check(h.opens==0);
p=new SplitPairing();h=new Fake();h.fail=true;p.start(h);check(p.snapshot().phase.equals("manual"));check(h.opens==1&&h.hints==1&&h.pending.isEmpty());
p=new SplitPairing();h=new Fake();p.start(h);h.multi=true;h.visible=false;h.finish();
check(p.snapshot().phase.equals("manual"));check(h.hints==1);
p=new SplitPairing();h=new Fake();p.start(h);for(int i=0;i<9;i++)h.tick();
check(p.snapshot().phase.equals("opening"));h.multi=true;h.tick();
check(p.snapshot().phase.equals("multiwindow"));check(h.hints==0);
p=new SplitPairing();h=new Fake();p.start(h);h.finish();check(p.snapshot().phase.equals("manual"));
h.multi=true;p.start(h);h.finish();check(p.snapshot().phase.equals("multiwindow"));check(h.opens==2&&h.hints==1);
p=new SplitPairing();h=new Fake();check(!p.multiWindowDetected());
p.start(h);check(p.multiWindowDetected());h.finish();
check(p.snapshot().phase.equals("multiwindow")&&h.hints==0);
p=new SplitPairing();h=new Fake();p.start(h);h.finish();
SplitPairing.Result timedOut=p.snapshot();check(timedOut.phase.equals("manual")&&h.hints==1);
check(p.multiWindowDetected());check(p.snapshot()!=timedOut&&p.snapshot().phase.equals("multiwindow"));
check(!p.multiWindowDetected());
System.out.println("PASS SplitPairing "+checks+" checks: version routing, actual window, duplicate, denial, timeout, retry");
}
}
Loading
Loading