Release v0.1.54: scheduled location sessions and paged voice delivery history

This commit is contained in:
Codex
2026-10-19 07:55:36 +08:00
parent ad2614719b
commit 4dc3e2fb9f
28 changed files with 481 additions and 153 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="9" android:versionName="0.1.53">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="10" android:versionName="0.1.54">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
+2 -1
View File
@@ -1,4 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="9" android:versionName="0.1.53">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="10" android:versionName="0.1.54">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
@@ -16,6 +16,7 @@
<service android:name=".MonitorService" android:exported="false"/>
<activity android:name=".LocationActivity" android:label="赵府家人位置" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location|dataSync"/>
<service android:name=".LocationSyncJob" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE"/>
<receiver android:name=".BootReceiver" android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
</application>
</manifest>
@@ -2,6 +2,11 @@ package cn.ucvl.zhaodisplay;
import android.content.*;
public class BootReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context,Intent intent){
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())&&context.getSharedPreferences("display",0).getBoolean("phoneMode",false)){
android.content.SharedPreferences p=context.getSharedPreferences("location",0);boolean was=p.getBoolean("active",false);
LocationSchedule.cancel(context);p.edit().putBoolean("active",false).putBoolean("stopPending",was||p.getBoolean("stopPending",false)).putString("status","手机已重启,请本人重新开启共享").apply();
if(was||p.getLong("pendingPoints",0)>0)LocationSchedule.retry(context,30000);
}
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) && !context.getSharedPreferences("display",0).getBoolean("phoneMode",false) && !context.getSharedPreferences("display",0).getString("token","").isEmpty())
context.startForegroundService(new Intent(context,MonitorService.class));
}
@@ -15,7 +15,7 @@ import java.util.*;
public class LocationActivity extends Activity {
static volatile boolean pairing=false;
TextView identity,status,viewStatus,permissionStatus;EditText code;Button pair,reload;
CheckBox consent,historyConsent;Switch sharing;Spinner cadence,sampleCadence,customUnit,sampleUnit;EditText customAmount,sampleAmount;LinearLayout customPeriod,samplePeriod,settings,recipients,familyList,homeContent,shareControls;
CheckBox consent,historyConsent;Switch sharing;Spinner sharingMode,cadence,sampleCadence,customUnit,sampleUnit;EditText customAmount,sampleAmount;LinearLayout customPeriod,samplePeriod,settings,recipients,familyList,homeContent,shareControls;
TextView queueStatus;LocationQueue outbox;String queueOwner="";
final int[] sampleIntervals={10,60,300,900,1800,3600,7200,10800,14400,18000,21600,43200,86400,0};
final int[] sampleUnits={1,60,3600,86400};
@@ -37,10 +37,11 @@ public class LocationActivity extends Activity {
getSharedPreferences("display",0).edit().putBoolean("phoneMode",true).apply();
stopService(new Intent(this,MonitorService.class));
// Process death/reboot cannot leave a stale switch claiming collection is active.
if(prefs.getBoolean("active",false)&&!LocationService.busy){
if(prefs.getBoolean("active",false)&&!LocationService.busy&&!LocationSchedule.enabled(prefs)){
prefs.edit().putBoolean("active",false).putString("status","共享已中断,请本人重新开启").apply();
startService(new Intent(this,LocationService.class).setAction("STOP"));
}
LocationSchedule.resume(this);
style=new PhoneStyle(this);phone=new PhoneLayout(this);setContentView(phone);
getWindow().setStatusBarColor(PhoneStyle.PAPER);getWindow().setNavigationBarColor(PhoneStyle.CARD);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
@@ -54,11 +55,16 @@ public class LocationActivity extends Activity {
text("只允许勾选的对象查看我的位置",19,recipientSection);
text("修改名单前先关闭共享。完成设置后,重新开启共享才会应用新的授权名单。",14,recipientSection);
recipients=style.column();recipientSection.addView(recipients);
text("定位采集频率",16,sampleSection);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒(较耗电)","每 1 分钟(默认)","每 5 分钟","每 15 分钟","每 30 分钟","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 6 小时","每 12 小时","每 1 天","自定义采集间隔"}));sampleCadence.setSelection(1);sampleSection.addView(sampleCadence);
text("位置共享模式",20,sampleSection);
sharingMode=new Spinner(this);sharingMode.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"定时采集与汇报(省电)","实时共享(持续在线)"}));sampleSection.addView(sharingMode);
text("定时:到点短暂定位,取得位置或 30 秒超时后释放定位;采集和上传分开设置。实时:持续定位,约每 10 秒汇报,保留运行通知。",14,sampleSection);
text("锁屏、省电或系统限制可能延后定时任务,不能保证精确到秒。手机重启后需要本人重新开启共享。",14,sampleSection);
sharingMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){public void onItemSelected(AdapterView<?> p,View v,int i,long id){if(sampleCadence!=null&&cadence!=null)render();}public void onNothingSelected(AdapterView<?> p){}});
text("定时采集频率",16,sampleSection);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒(较耗电)","每 1 分钟(默认)","每 5 分钟","每 15 分钟","每 30 分钟","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 6 小时","每 12 小时","每 1 天","自定义采集间隔"}));sampleCadence.setSelection(1);sampleSection.addView(sampleCadence);
samplePeriod=new LinearLayout(this);samplePeriod.setOrientation(LinearLayout.HORIZONTAL);sampleAmount=new EditText(this);sampleAmount.setInputType(InputType.TYPE_CLASS_NUMBER);sampleAmount.setHint("正整数");sampleAmount.setText("2");sampleAmount.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(5)});samplePeriod.addView(sampleAmount,new LinearLayout.LayoutParams(0,-2,1));sampleUnit=new Spinner(this);sampleUnit.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"秒","分钟","小时","天"}));sampleUnit.setSelection(2);samplePeriod.addView(sampleUnit);sampleSection.addView(samplePeriod);samplePeriod.setVisibility(View.GONE);
sampleCadence.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){public void onItemSelected(AdapterView<?> p,View v,int position,long id){samplePeriod.setVisibility(position==sampleIntervals.length-1?View.VISIBLE:View.GONE);}public void onNothingSelected(AdapterView<?> p){}});
text("每次采集留下一个定位点。可自定义 10 秒至 24 小时,最长每天一次,不设一周。采集越稀疏越省电,但无法还原期间的完整路线。",14,sampleSection);
text("集中上传周期",16,uploadSection);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"实时(约 10 秒)","每 1 分钟","每 5 分钟(默认)","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 1 天","每 2 天","每 3 天","自定义小时 / 天"}));cadence.setSelection(2);uploadSection.addView(cadence);
text("集中上传周期",16,uploadSection);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒","每 1 分钟","每 5 分钟(默认)","每 1 小时","每 2 小时","每 3 小时","每 4 小时","每 5 小时","每 1 天","每 2 天","每 3 天","自定义小时 / 天"}));cadence.setSelection(2);uploadSection.addView(cadence);
customPeriod=new LinearLayout(this);customPeriod.setOrientation(0);customAmount=new EditText(this);customAmount.setInputType(InputType.TYPE_CLASS_NUMBER);customAmount.setHint("正整数");customAmount.setText("6");customAmount.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(3)});customPeriod.addView(customAmount,new LinearLayout.LayoutParams(0,-2,1));customUnit=new Spinner(this);customUnit.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"小时","天"}));customPeriod.addView(customUnit);uploadSection.addView(customPeriod);customPeriod.setVisibility(View.GONE);
cadence.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){public void onItemSelected(AdapterView<?> p,View v,int position,long id){customPeriod.setVisibility(position==uploadIntervals.length-1?View.VISIBLE:View.GONE);}public void onNothingSelected(AdapterView<?> p){}});
text("采集与上传分开:例如每分钟采集、每天集中上传。自定义 1—720 小时或 1—30 天。断网时本地暂存,恢复后自动补传;长周期期间家人无法看到实时移动。调整名单或频率前,先关闭共享。",14,uploadSection);
@@ -88,7 +94,7 @@ public class LocationActivity extends Activity {
phone.myCheck.setOnClickListener(v->{if(pairingRequired())showDetail("配对我的手机",pairSection);else showDetail("定位权限",permissionSection);});phone.permissions.setOnClickListener(v->showDetail("定位权限与系统设置",permissionSection));
phone.viewers.setOnClickListener(v->{if(!settingsReady)loadSettings();showDetail("允许谁查看",recipientSection);});
phone.expiry.setOnClickListener(v->new AlertDialog.Builder(this).setTitle("共享有效期").setMessage(prefs.getLong("expires",0)>0?"本手机配对有效至 "+java.text.DateFormat.getDateTimeInstance().format(new Date(prefs.getLong("expires",0)))+"。到期后停止新位置共享;可随时手动关闭。续期或重新配对请联系家庭管理员。":"配对后显示有效期。").setPositiveButton("知道了",null).show());
phone.sampling.setOnClickListener(v->showDetail("定位采集频率",sampleSection));phone.upload.setOnClickListener(v->showDetail("集中上传与离线暂存",uploadSection));phone.history.setOnClickListener(v->showDetail("我的历史轨迹",historySection));
phone.sampling.setOnClickListener(v->showDetail("共享模式与采集频率",sampleSection));phone.upload.setOnClickListener(v->showDetail("集中上传与离线暂存",uploadSection));phone.history.setOnClickListener(v->showDetail("我的历史轨迹",historySection));
selectTab(paired()?0:2);render();
}
boolean paired(){return !prefs.getString("token","").isEmpty();}
@@ -109,7 +115,7 @@ public class LocationActivity extends Activity {
if(total==0){showDetail("先选择查看人",recipientSection);Toast.makeText(this,"请先选择允许查看你位置的家人或显示终端",1).show();return;}
try{samplePeriodSeconds();uploadPeriod();}catch(Exception e){Toast.makeText(this,"请先检查定位频率和上传周期",1).show();return;}
if(consentSection.getParent()!=null)((android.view.ViewGroup)consentSection.getParent()).removeView(consentSection);consent.setChecked(false);
new AlertDialog.Builder(this).setTitle("开启我的位置共享").setMessage("允许 "+total+" 个对象查看 · 采集"+periodLabel(samplePeriodSeconds())+" · 上传"+periodLabel(uploadPeriod())+"。\n可随时关闭。频率与名单将在此次开启时生效。").setView(consentSection).setNegativeButton("暂不开启",null).setPositiveButton("开启共享",(d,w)->start()).setOnDismissListener(d->{if(consentSection.getParent()!=null)((android.view.ViewGroup)consentSection.getParent()).removeView(consentSection);settings.addView(consentSection);render();}).show();
new AlertDialog.Builder(this).setTitle("开启我的位置共享").setMessage((realtimeMode()?"实时共享:持续定位与汇报。\n":"定时共享:采集完即释放定位。\n")+"允许 "+total+" 个对象查看 · 采集"+periodLabel(samplePeriodSeconds())+" · 上传"+periodLabel(uploadPeriod())+"。\n可随时关闭。频率与名单将在此次开启时生效。").setView(consentSection).setNegativeButton("暂不开启",null).setPositiveButton("开启共享",(d,w)->start()).setOnDismissListener(d->{if(consentSection.getParent()!=null)((android.view.ViewGroup)consentSection.getParent()).removeView(consentSection);settings.addView(consentSection);render();}).show();
}
String periodLabel(int seconds){return "每 "+(seconds%86400==0?seconds/86400+" 天":seconds%3600==0?seconds/3600+" 小时":seconds%60==0?seconds/60+" 分钟":seconds+" 秒");}
public void onBackPressed(){if(phone.tab!=0){selectTab(0);return;}super.onBackPressed();}
@@ -127,20 +133,20 @@ public class LocationActivity extends Activity {
VoiceSurface.text(phone.check,pairingRequired()?"去配对":"检查");VoiceSurface.text(phone.myCheck,pairingRequired()?"重新配对":"检查权限");
phone.expiry.value(expires>0?java.text.DateFormat.getDateInstance().format(new Date(expires))+" 到期":"尚未配对");
int viewers=0;for(List<CheckBox> list:choices.values())for(CheckBox c:list)if(c.isChecked())viewers++;phone.viewers.value(settingsReady?viewers+" 个已选对象 · "+(active?"共享期间生效":"开启共享后生效"):"点击读取授权名单");
try{phone.sampling.value(periodLabel(samplePeriodSeconds()));phone.upload.value(periodLabel(uploadPeriod())+" · 断网时加密暂存");}catch(Exception e){phone.sampling.value("请检查自定义间隔");}
try{phone.sampling.value(realtimeMode()?"实时共享 · 持续定位":"定时采集 · "+periodLabel(samplePeriodSeconds()));phone.upload.value(realtimeMode()?"约每 10 秒 · 持续在线":periodLabel(uploadPeriod())+" · 断网时加密暂存");}catch(Exception e){phone.sampling.value("请检查自定义间隔");}
phone.history.value((historyConsent.isChecked()?"已选择保存轨迹":"未选择保存轨迹")+" · "+prefs.getLong("pendingPoints",0)+" 个点待同步");
phone.permissions.value(locationPermissionText());
queueStatus.setText(String.format(Locale.CHINA,"本机待同步:%d 个点 · %.1f KB\n累计校验清理:%d 个点 · %.1f KB\n%s%s",prefs.getLong("pendingPoints",0),prefs.getLong("pendingBytes",0)/1024d,prefs.getLong("uploadedPoints",0),prefs.getLong("freedBytes",0)/1024d,prefs.getBoolean("cacheFull",false)?"缓存已满,暂停新增历史。\n":"",prefs.getString("syncStatus","尚无待同步轨迹")));
rendering=true;sharing.setChecked(active);rendering=false;
sharing.setEnabled(paired&&!pairing&&(active||!pairingRequired()&&!busy&&settingsReady));
pair.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);historyConsent.setEnabled(!active&&!busy&&settingsReady);
sampleCadence.setEnabled(!active&&!busy);sampleAmount.setEnabled(!active&&!busy);sampleUnit.setEnabled(!active&&!busy);customAmount.setEnabled(!active&&!busy);customUnit.setEnabled(!active&&!busy);
sharingMode.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy&&!realtimeMode());sampleCadence.setEnabled(!active&&!busy&&!realtimeMode());sampleAmount.setEnabled(!active&&!busy&&!realtimeMode());sampleUnit.setEnabled(!active&&!busy&&!realtimeMode());customAmount.setEnabled(!active&&!busy&&!realtimeMode());customUnit.setEnabled(!active&&!busy&&!realtimeMode());
for(List<CheckBox> list:choices.values())for(CheckBox c:list)c.setEnabled(!active&&!busy);
reload.setEnabled(paired&&!loading&&!pairing);
}
void remember(JSONObject response)throws Exception{
StringBuilder names=new StringBuilder();for(String type:new String[]{"viewers","phones","displays"}){JSONArray list=response.optJSONArray(type);if(list==null)continue;for(int i=0;i<list.length();i++){if(names.length()>0)names.append("、");names.append(list.getJSONObject(i).getString("name"));if(type.equals("displays"))names.append("(显示终端)");}}
prefs.edit().putString("receipt",response.getString("receipt")).putString("recipients",names.toString()).putInt("intervalSeconds",response.optInt("intervalSeconds",300)).putInt("sampleIntervalSeconds",response.optInt("sampleIntervalSeconds",60)).apply();
prefs.edit().putString("receipt",response.getString("receipt")).putString("recipients",names.toString()).putString("sharingMode",response.optString("sharingMode","scheduled")).putInt("intervalSeconds",response.optInt("intervalSeconds",300)).putInt("sampleIntervalSeconds",response.optInt("sampleIntervalSeconds",60)).apply();
}
void pair(){
if(pairing||LocationService.busy||prefs.getBoolean("active",false))return;
@@ -149,7 +155,7 @@ public class LocationActivity extends Activity {
pairing=true;render();
new Thread(()->{try{
JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",3));remember(response);
stopService(new Intent(this,LocationService.class));prefs.edit().putString("memberName",response.getString("memberName")).putString("token",response.getString("token")).putString("home",response.getString("home")).putLong("expires",(long)(response.getDouble("expires")*1000)).putBoolean("active",false).putString("status","已配对;共享关闭,可查看获授权家人").apply();refreshQueueStats();
LocationSchedule.cancel(this);stopService(new Intent(this,LocationService.class));prefs.edit().putString("memberName",response.getString("memberName")).putString("token",response.getString("token")).putString("home",response.getString("home")).putLong("expires",(long)(response.getDouble("expires")*1000)).putBoolean("active",false).putString("status","已配对;共享关闭,可查看获授权家人").apply();refreshQueueStats();
runOnUiThread(()->{if(isDestroyed())return;pairing=false;bindingRejected=false;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;if(detailDialog!=null)detailDialog.dismiss();selectTab(0);voice.rebound();loadSettings();loadFamily();});
}catch(Exception e){runOnUiThread(()->{if(!isDestroyed())Toast.makeText(this,"配对未成功,请检查手机配对码或安装新版 App",1).show();});}finally{pairing=false;runOnUiThread(()->{if(!isDestroyed())render();});}},"location-pair").start();
}
@@ -176,7 +182,7 @@ public class LocationActivity extends Activity {
JSONObject result=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","settings"));
runOnUiThread(()->{if(!visible||g!=generation||request!=settingsRequest)return;settingsReceipt=result.optString("receipt");recipients.removeAllViews();choices.clear();
for(String type:new String[]{"viewers","phones","displays"}){String key=type.equals("viewers")?"viewerIds":type.equals("phones")?"phoneIds":"displayIds";text(type.equals("viewers")?"平台查看账号":type.equals("phones")?"已配对的家人手机":"公共显示终端",16,recipients);JSONArray options=result.optJSONArray(type),selected=result.optJSONArray(key);Set<String> ids=new HashSet<>();if(selected!=null)for(int i=0;i<selected.length();i++)ids.add(selected.optString(i));List<CheckBox> list=new ArrayList<>();choices.put(key,list);if(options!=null)for(int i=0;i<options.length();i++){JSONObject item=options.optJSONObject(i);CheckBox c=new CheckBox(this);c.setText(item.optString("name"));c.setTag(item.optString("id"));c.setChecked(ids.contains(item.optString("id")));recipients.addView(c);list.add(c);}if(list.isEmpty())text("暂无可选对象",14,recipients);}
int seconds=result.optInt("intervalSeconds",300);setUploadPeriod(seconds);setSamplePeriod(result.optInt("sampleIntervalSeconds",60));historyAcknowledged=result.optBoolean("historyEnabled",false);historyConsent.setChecked(historyAcknowledged||result.optBoolean("historyDefault",false));JSONObject h=result.optJSONObject("history");if(h!=null)historyStatus.setText("待归档 "+h.optInt("pending")+" 个定位点 · 已归档 "+h.optInt("archived")+" 段 · 待删除 "+h.optInt("deleting")+" 段\n"+h.optString("error")+"\n长期保留,由本人手动删除。修改设置前先关闭共享。");settingsReady=true;render();});
sharingMode.setSelection("realtime".equals(result.optString("sharingMode","scheduled"))?1:0);int seconds=result.optInt("intervalSeconds",300);setUploadPeriod(seconds);setSamplePeriod(result.optInt("sampleIntervalSeconds",60));historyAcknowledged=result.optBoolean("historyEnabled",false);historyConsent.setChecked(historyAcknowledged||result.optBoolean("historyDefault",false));JSONObject h=result.optJSONObject("history");if(h!=null)historyStatus.setText("待归档 "+h.optInt("pending")+" 个定位点 · 已归档 "+h.optInt("archived")+" 段 · 待删除 "+h.optInt("deleting")+" 段\n"+h.optString("error")+"\n长期保留,由本人手动删除。修改设置前先关闭共享。");settingsReady=true;render();});
}catch(Exception e){runOnUiThread(()->{if(visible&&g==generation&&request==settingsRequest){settingsReady=false;if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403))bindingRejected=true;settingsError="无法读取我的位置设置,请检查网络或配对有效期,重新打开设置重试。";render();}});}},"location-settings").start();
}
void start(){
@@ -184,20 +190,22 @@ public class LocationActivity extends Activity {
if(!consent.isChecked()){Toast.makeText(this,"请本人核对并勾选共享说明",1).show();return;}
if(historyConsent.isChecked()&&!historyAcknowledged){new AlertDialog.Builder(this).setTitle("同意长期保存我的轨迹").setMessage("定位点将加密上传家庭百度网盘,按天、周、月、年或全部历史查看,长期保留直到你手动删除。共享时所选查看人能读取其获授权期间的历史。关闭实时共享不会删除历史。是否同意?").setNegativeButton("暂不启用",null).setPositiveButton("本人同意并开启",(d,w)->{historyAcknowledged=true;start();}).show();return;}
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},45);return;}
if(!realtimeMode()&&Build.VERSION.SDK_INT>=29&&checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)!=PackageManager.PERMISSION_GRANTED){backgroundPermission();return;}
if(!LocationService.locationEnabled((android.location.LocationManager)getSystemService(LOCATION_SERVICE))){Toast.makeText(this,"请先打开手机系统定位开关",1).show();return;}
final JSONObject body=new JSONObject();try{int total=0;for(Map.Entry<String,List<CheckBox>> e:choices.entrySet()){JSONArray ids=new JSONArray();for(CheckBox c:e.getValue())if(c.isChecked()){ids.put((String)c.getTag());total++;}body.put(e.getKey(),ids);}if(total==0){Toast.makeText(this,"请选择至少一位查看人;只看家人无需开启此开关",1).show();return;}int upload=uploadPeriod();if(upload>=3600&&!historyConsent.isChecked()){Toast.makeText(this,"按小时或天集中上传需要本人启用历史保存,才能保留期间的轨迹",1).show();return;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",upload).put("sampleIntervalSeconds",samplePeriodSeconds()).put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){Toast.makeText(this,"采集间隔需为 10 秒至 1 天;上传周期为 1—720 小时或 1—30 天,均填正整数",1).show();return;}
final JSONObject body=new JSONObject();try{int total=0;for(Map.Entry<String,List<CheckBox>> e:choices.entrySet()){JSONArray ids=new JSONArray();for(CheckBox c:e.getValue())if(c.isChecked()){ids.put((String)c.getTag());total++;}body.put(e.getKey(),ids);}if(total==0){Toast.makeText(this,"请选择至少一位查看人;只看家人无需开启此开关",1).show();return;}int upload=uploadPeriod();if(upload>=3600&&!historyConsent.isChecked()){Toast.makeText(this,"按小时或天集中上传需要本人启用历史保存,才能保留期间的轨迹",1).show();return;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",upload).put("sampleIntervalSeconds",samplePeriodSeconds()).put("sharingMode",realtimeMode()?"realtime":"scheduled").put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){Toast.makeText(this,"采集间隔需为 10 秒至 1 天;上传周期为 1—720 小时或 1—30 天,均填正整数",1).show();return;}
final int g=generation;final String token=prefs.getString("token","");pairing=true;settingsReady=false;settingsError="";render();
new Thread(()->{try{JSONObject result=DisplayApi.call("/api/location/update",token,body);remember(result);runOnUiThread(()->{if(!visible||g!=generation)return;settingsReceipt=result.optString("receipt");settingsReady=true;LocationService.busy=true;try{startForegroundService(new Intent(this,LocationService.class).setAction("START"));}catch(Exception e){LocationService.busy=false;Toast.makeText(this,"未能启动定位,请保持页面在前台再试",1).show();}render();});}
catch(Exception e){runOnUiThread(()->{if(visible&&g==generation)Toast.makeText(this,"开启未成功,请重新读取设置并核对名单",1).show();});}
finally{pairing=false;runOnUiThread(()->{if(!isDestroyed()){if(visible&&!settingsReady)loadSettings();render();}});}},"location-configure").start();
}
int samplePeriodSeconds(){int index=sampleCadence.getSelectedItemPosition();return sampleIntervals[index]>0?sampleIntervals[index]:LocationCadence.customSample(Integer.parseInt(sampleAmount.getText().toString().trim()),sampleUnits[sampleUnit.getSelectedItemPosition()]);}
boolean realtimeMode(){return sharingMode!=null&&sharingMode.getSelectedItemPosition()==1;}
int samplePeriodSeconds(){if(realtimeMode())return 10;int index=sampleCadence.getSelectedItemPosition();return sampleIntervals[index]>0?sampleIntervals[index]:LocationCadence.customSample(Integer.parseInt(sampleAmount.getText().toString().trim()),sampleUnits[sampleUnit.getSelectedItemPosition()]);}
void setSamplePeriod(int seconds){seconds=LocationCadence.sample(seconds);for(int i=0;i<sampleIntervals.length-1;i++)if(sampleIntervals[i]==seconds){sampleCadence.setSelection(i);return;}sampleCadence.setSelection(sampleIntervals.length-1);int unit=seconds%86400==0?3:seconds%3600==0?2:seconds%60==0?1:0;sampleUnit.setSelection(unit);sampleAmount.setText(Integer.toString(seconds/sampleUnits[unit]));}
int uploadPeriod(){int index=cadence.getSelectedItemPosition();return uploadIntervals[index]>0?uploadIntervals[index]:LocationCadence.custom(Integer.parseInt(customAmount.getText().toString().trim()),customUnit.getSelectedItemPosition()==1);}
int uploadPeriod(){if(realtimeMode())return 10;int index=cadence.getSelectedItemPosition();return uploadIntervals[index]>0?uploadIntervals[index]:LocationCadence.custom(Integer.parseInt(customAmount.getText().toString().trim()),customUnit.getSelectedItemPosition()==1);}
void setUploadPeriod(int seconds){for(int i=0;i<uploadIntervals.length-1;i++)if(uploadIntervals[i]==seconds){cadence.setSelection(i);return;}cadence.setSelection(uploadIntervals.length-1);boolean days=seconds%86400==0;customUnit.setSelection(days?1:0);customAmount.setText(Integer.toString(seconds/(days?86400:3600)));}
void refreshQueueStats(){try{queueOwner=LocationQueue.digest(prefs.getString("token",""));long[] values=outbox.stats(queueOwner);prefs.edit().putLong("pendingPoints",values[0]).putLong("pendingBytes",values[1]).putLong("uploadedPoints",values[2]).putLong("freedBytes",values[3]).apply();}catch(Exception e){prefs.edit().putString("syncStatus","本机轨迹暂不能读取,数据没有删除").apply();}}
void syncNow(){if(prefs.getString("token","").isEmpty())return;try{startForegroundService(new Intent(this,LocationService.class).setAction("SYNC"));Toast.makeText(this,"已开始同步;只有网盘完整校验后才清理本机记录",0).show();}catch(Exception e){Toast.makeText(this,"请保持页面打开再试一次",1).show();}}
void discardLocal(){prefs.edit().putLong("queueEpoch",System.currentTimeMillis()).commit();stopService(new Intent(this,LocationService.class));outbox.discard(queueOwner);prefs.edit().putBoolean("active",false).putBoolean("cacheFull",false).putString("syncStatus","已按本人要求放弃本机待同步副本").apply();refreshQueueStats();startService(new Intent(this,LocationService.class).setAction("STOP"));render();}
void discardLocal(){prefs.edit().putLong("queueEpoch",System.currentTimeMillis()).commit();LocationSchedule.cancel(this);stopService(new Intent(this,LocationService.class));outbox.discard(queueOwner);prefs.edit().putBoolean("active",false).putBoolean("cacheFull",false).putString("syncStatus","已按本人要求放弃本机待同步副本").apply();refreshQueueStats();startService(new Intent(this,LocationService.class).setAction("STOP"));render();}
void history(String member){
new AlertDialog.Builder(this).setTitle("查看历史时段").setItems(new String[]{"每天","每周","每月","每年","一生 · 全部已存记录"},(dialog,choice)->{
String period=new String[]{"day","week","month","year","life"}[choice];Calendar c=Calendar.getInstance();
@@ -223,7 +231,7 @@ public class LocationActivity extends Activity {
final Dialog shown=historyDialog;ui.postDelayed(()->{if(shown.isShowing())shown.dismiss();},60000);
});}catch(Exception e){runOnUiThread(()->{if(visible&&g==generation&&request==historyRequest){if(historyDialog!=null)historyDialog.dismiss();Toast.makeText(this,"未能读取:请检查本人授权、日期和网盘连接",1).show();}});}},"location-history").start();
}
void deleteHistory(){int g=generation;prefs.edit().putLong("queueEpoch",System.currentTimeMillis()).commit();stopService(new Intent(this,LocationService.class));prefs.edit().putBoolean("active",false).apply();new Thread(()->{try{String token=prefs.getString("token","");DisplayApi.call("/api/location/update",token,new JSONObject().put("action","stop"));DisplayApi.call("/api/location/update",token,new JSONObject().put("action","history-delete").put("confirm",true));outbox.discard(queueOwner);refreshQueueStats();runOnUiThread(()->{if(visible&&g==generation){Toast.makeText(this,"本机待同步已清理,历史已隐藏,云端删除会持续重试",1).show();loadSettings();}});}catch(Exception e){runOnUiThread(()->Toast.makeText(this,"删除未完成,本机待同步记录保留,请检查连接后重试",1).show());}},"delete-history").start();}
void deleteHistory(){int g=generation;prefs.edit().putLong("queueEpoch",System.currentTimeMillis()).commit();LocationSchedule.cancel(this);stopService(new Intent(this,LocationService.class));prefs.edit().putBoolean("active",false).apply();new Thread(()->{try{String token=prefs.getString("token","");DisplayApi.call("/api/location/update",token,new JSONObject().put("action","stop"));DisplayApi.call("/api/location/update",token,new JSONObject().put("action","history-delete").put("confirm",true));outbox.discard(queueOwner);refreshQueueStats();runOnUiThread(()->{if(visible&&g==generation){Toast.makeText(this,"本机待同步已清理,历史已隐藏,云端删除会持续重试",1).show();loadSettings();}});}catch(Exception e){runOnUiThread(()->Toast.makeText(this,"删除未完成,本机待同步记录保留,请检查连接后重试",1).show());}},"delete-history").start();}
String locationPermissionText(){
boolean foreground=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==0||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==0;
if(!foreground)return "定位权限:未允许。查看家人不需要开启自己的定位。";
@@ -243,7 +251,7 @@ public class LocationActivity extends Activity {
}).show();
}
public void onRequestPermissionsResult(int request,String[] permissions,int[] results){super.onRequestPermissionsResult(request,permissions,results);if(request==47||request==48){render();return;}if(request==45){if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==0||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==0){if(visible)start();else pendingStart=true;}else Toast.makeText(this,"未授权定位,不采集自己的位置;仍可查看获授权家人",1).show();render();}}
public void onResume(){super.onResume();visible=true;map.resumeMap();voice.active(true);lastList=0;refreshQueueStats();if(!LocationService.busy&&prefs.getLong("pendingPoints",0)>0)syncNow();if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}}
public void onResume(){super.onResume();visible=true;map.resumeMap();voice.active(true);lastList=0;refreshQueueStats();if(!LocationService.busy&&(prefs.getBoolean("reportPending",false)||prefs.getBoolean("stopPending",false)))syncNow();if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}}
public void onPause(){visible=false;if(historyDialog!=null)historyDialog.dismiss();voice.active(false);generation++;loading=false;ui.removeCallbacksAndMessages(null);if(map!=null)map.pauseMap();if(familyList!=null)familyList.removeAllViews();super.onPause();}
public void onDestroy(){if(detailDialog!=null)detailDialog.dismiss();if(map!=null)map.close();if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();}
}
@@ -16,14 +16,20 @@ final class LocationQueue extends SQLiteOpenHelper {
static final int MAX_POINTS=50000, BATCH_POINTS=128, MAX_INFLIGHT=4;
static final long MAX_BYTES=12L*1024*1024, MAX_DATABASE_BYTES=32L*1024*1024;
static final String KEY="zhao-location-outbox-v1";
LocationQueue(Context context){super(context,"location-outbox.db",null,1);}
LocationQueue(Context context){super(context,"location-outbox.db",null,2);}
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE points(id TEXT PRIMARY KEY,owner TEXT NOT NULL,session TEXT NOT NULL,at INTEGER,payload BLOB NOT NULL,batch TEXT)");
db.execSQL("CREATE INDEX queue_owner ON points(owner,at)");
db.execSQL("CREATE TABLE batches(id TEXT PRIMARY KEY,owner TEXT,session TEXT,payload BLOB,digest TEXT,count INTEGER,next_try INTEGER)");
db.execSQL("CREATE TABLE totals(owner TEXT PRIMARY KEY,uploaded INTEGER NOT NULL,freed INTEGER NOT NULL)");
db.execSQL("CREATE TABLE latest(owner TEXT PRIMARY KEY,payload BLOB NOT NULL)");
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){throw new IllegalStateException("Unsupported location outbox migration");}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){if(oldVersion==1&&newVersion==2)db.execSQL("CREATE TABLE latest(owner TEXT PRIMARY KEY,payload BLOB NOT NULL)");else throw new IllegalStateException("Unsupported location outbox migration");}
synchronized void latest(String owner,JSONObject fix)throws Exception{ContentValues row=new ContentValues();row.put("owner",owner);row.put("payload",encrypt(fix.toString(),owner+"latest"));getWritableDatabase().insertWithOnConflict("latest",null,row,SQLiteDatabase.CONFLICT_REPLACE);}
synchronized JSONObject latest(String owner)throws Exception{try(Cursor c=getReadableDatabase().rawQuery("SELECT payload FROM latest WHERE owner=?",new String[]{owner})){return c.moveToFirst()?new JSONObject(decrypt(c.getBlob(0),owner+"latest")):null;}}
synchronized void clearLatest(String owner){getWritableDatabase().delete("latest","owner=?",new String[]{owner});}
synchronized boolean hasBatches(String owner){try(Cursor c=getReadableDatabase().rawQuery("SELECT 1 FROM batches WHERE owner=? LIMIT 1",new String[]{owner})){return c.moveToFirst();}}
synchronized boolean ready(String owner,long cutoff){try(Cursor c=getReadableDatabase().rawQuery("SELECT 1 FROM points WHERE owner=? AND (batch IS NOT NULL OR at<=?) LIMIT 1",new String[]{owner,Long.toString(cutoff)})){return c.moveToFirst();}}
public void onOpen(SQLiteDatabase db){super.onOpen(db);db.setMaximumSize(MAX_DATABASE_BYTES);try(Cursor c=db.rawQuery("PRAGMA secure_delete=ON",null)){c.moveToFirst();}}
static String id(){return UUID.randomUUID().toString().replace("-","");}
static String digest(String value)throws Exception{
@@ -91,5 +97,5 @@ final class LocationQueue extends SQLiteOpenHelper {
return values;
}
synchronized long total(){try(Cursor c=getReadableDatabase().rawQuery("SELECT count(*) FROM points",null)){c.moveToFirst();return c.getLong(0);}}
synchronized void discard(String owner){SQLiteDatabase db=getWritableDatabase();db.beginTransaction();try{db.delete("points","owner=?",new String[]{owner});db.delete("batches","owner=?",new String[]{owner});db.setTransactionSuccessful();}finally{db.endTransaction();}}
synchronized void discard(String owner){SQLiteDatabase db=getWritableDatabase();db.beginTransaction();try{db.delete("points","owner=?",new String[]{owner});db.delete("batches","owner=?",new String[]{owner});db.delete("latest","owner=?",new String[]{owner});db.setTransactionSuccessful();}finally{db.endTransaction();}}
}
@@ -0,0 +1,32 @@
package cn.ucvl.zhaodisplay;
import android.app.*;
import android.app.job.*;
import android.content.*;
import android.os.*;
/** OS-owned, inexact wakeups. No timer thread, GPS listener or process between samples. */
final class LocationSchedule {
static final int SAMPLE=4501,REPORT=4502,RETRY=4503;
static boolean scheduled(SharedPreferences p){return "scheduled".equals(p.getString("sharingMode","scheduled"));}
static boolean enabled(SharedPreferences p){return p.getBoolean("active",false)&&scheduled(p)&&p.getLong("expires",0)>System.currentTimeMillis()&&!p.getString("sessionToken","").isEmpty()&&p.getString("sessionToken","").equals(p.getString("token",""));}
static PendingIntent intent(Context c,int id){
Intent i=new Intent(c,LocationService.class).setAction(id==SAMPLE?"SAMPLE":"REPORT");
i.putExtra("session",c.getSharedPreferences("location",0).getString("sessionNonce",""));
return PendingIntent.getForegroundService(c,id,i,PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE);
}
static void arm(Context c,int id,long at){((AlarmManager)c.getSystemService(Context.ALARM_SERVICE)).setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,Math.max(System.currentTimeMillis()+1000,at),intent(c,id));}
static void resume(Context c){
SharedPreferences p=c.getSharedPreferences("location",0);if(!enabled(p))return;
arm(c,SAMPLE,p.getLong("nextSampleAt",System.currentTimeMillis()));
arm(c,REPORT,p.getLong("nextReportAt",System.currentTimeMillis()));
}
static void retry(Context c,long delay){
SharedPreferences p=c.getSharedPreferences("location",0);if(p.getString("token","").isEmpty())return;
PersistableBundle extras=new PersistableBundle();extras.putString("token",p.getString("token",""));
((JobScheduler)c.getSystemService(Context.JOB_SCHEDULER_SERVICE)).schedule(new JobInfo.Builder(RETRY,new ComponentName(c,LocationSyncJob.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setMinimumLatency(Math.max(10000,delay)).setExtras(extras).build());
}
static void cancelSampling(Context c){AlarmManager a=(AlarmManager)c.getSystemService(Context.ALARM_SERVICE);for(int id:new int[]{SAMPLE,REPORT})a.cancel(intent(c,id));}
static void cancel(Context c){cancelSampling(c);((JobScheduler)c.getSystemService(Context.JOB_SCHEDULER_SERVICE)).cancel(RETRY);}
}
@@ -10,135 +10,176 @@ import android.Manifest;
import org.json.JSONObject;
import java.util.concurrent.*;
/** Visible sharing plus an encrypted outbox. No boot receiver starts GPS collection. */
/** Continuous GPS only for explicit realtime mode. Scheduled sessions sleep between bounded work. */
public class LocationService extends Service implements LocationListener {
static volatile boolean busy=false;
String sessionToken="",owner="",collection="";
volatile boolean destroyed=false,active=false,stopping=false,starting=false,forceSync=false,failedNetwork=false,networkBlocked=false;
boolean historyEnabled=false,sentFix=false,cacheFull=false,ticking=false;
ScheduledExecutorService worker;ExecutorService recorder;LocationManager manager;LocationQueue queue;ConnectivityManager connectivity;
android.content.SharedPreferences prefs;volatile Location latest;
long lastUpload=0,lastSample=0,flushCutoff=0,collectionStarted=0;volatile long nextAttempt=0;
int failures=0,intervalSeconds=300,sampleSeconds=60;String lastSignal="";
volatile boolean destroyed=false,active=false,stopping=false,starting=false,forceSync=false,networkBlocked=false;
volatile boolean realtime=false,capturing=false;boolean historyEnabled=false,cacheFull=false,finishing=false;
ScheduledExecutorService worker;LocationManager manager;LocationQueue queue;ConnectivityManager connectivity;
SharedPreferences prefs;PowerManager.WakeLock wake;
long collectionStarted=0,captureStarted=0,lastSample=0,deadline=0;
int intervalSeconds=300,sampleSeconds=60;
final Handler ui=new Handler();
final Runnable captureTimeout=()->finishCapture("本次未取得新位置,等待下次采集");
final Runnable workTimeout=()->{if(!realtime){try{LocationSchedule.retry(this,60000);}catch(Exception ignored){}finishWork();}};
final ConnectivityManager.NetworkCallback networkCallback=new ConnectivityManager.NetworkCallback(){
public void onAvailable(Network network){nextAttempt=0;}
public void onLost(Network network){failedNetwork=true;}
public void onBlockedStatusChanged(Network network,boolean blocked){networkBlocked=blocked;if(blocked)failedNetwork=true;else if(failedNetwork){forceSync=true;nextAttempt=0;}}
public void onCapabilitiesChanged(Network network,NetworkCapabilities caps){if(failedNetwork&&caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED))nextAttempt=0;}
public void onBlockedStatusChanged(Network n,boolean blocked){networkBlocked=blocked;}
};
public void onCreate(){
super.onCreate();prefs=getSharedPreferences("location",0);manager=(LocationManager)getSystemService(LOCATION_SERVICE);queue=new LocationQueue(this);
sessionToken=prefs.getString("token","");try{owner=LocationQueue.digest(sessionToken);}catch(Exception e){stopSelf();return;}
sessionToken=prefs.getString("token","");try{owner=LocationQueue.digest(sessionToken);}catch(Exception ignored){}
NotificationManager nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);nm.createNotificationChannel(new NotificationChannel("location","本人位置与轨迹同步",NotificationManager.IMPORTANCE_LOW));
connectivity=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);worker=Executors.newSingleThreadScheduledExecutor();recorder=Executors.newSingleThreadExecutor();
connectivity=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);worker=Executors.newSingleThreadScheduledExecutor();
try{connectivity.registerDefaultNetworkCallback(networkCallback);}catch(Exception ignored){}
}
boolean validIdentity(){return !destroyed&&sessionToken.equals(prefs.getString("token",""));}
void notification(String text){
PendingIntent stop=PendingIntent.getService(this,1,new Intent(this,LocationService.class).setAction("STOP"),PendingIntent.FLAG_IMMUTABLE|PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent open=PendingIntent.getActivity(this,1,new Intent(this,LocationActivity.class),PendingIntent.FLAG_IMMUTABLE|PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder notice=new Notification.Builder(this,"location").setContentTitle(active||starting?"赵府 · 位置共享":"赵府 · 轨迹同步").setContentText(text).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentIntent(open).setOngoing(true);
if(active||starting)notice.addAction(new Notification.Action.Builder(null,"停止共享",stop).build());
if(Build.VERSION.SDK_INT>=29)startForeground(45,notice.build(),active||starting?android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION:android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);else startForeground(45,notice.build());
Notification.Builder n=new Notification.Builder(this,"location").setContentTitle(realtime?"赵府 · 实时共享":"赵府 · 本次定位与同步").setContentText(text).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentIntent(open).setOngoing(true);
if(active||starting)n.addAction(new Notification.Action.Builder(null,"停止共享",stop).build());
if(Build.VERSION.SDK_INT>=29)startForeground(45,n.build(),capturing||realtime?android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION:android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);else startForeground(45,n.build());
}
void bounded(){
deadline=SystemClock.elapsedRealtime()+90000;ui.removeCallbacks(workTimeout);ui.postDelayed(workTimeout,90000);
if(wake==null){wake=((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"zhao:location-cycle");wake.setReferenceCounted(false);}wake.acquire(95000);
}
public int onStartCommand(Intent intent,int flags,int id){
if(intent==null||sessionToken.isEmpty()){stopSelf();return START_NOT_STICKY;}
if(!ticking){ticking=true;worker.scheduleWithFixedDelay(this::tick,1,10,TimeUnit.SECONDS);}
notification("正在处理本次定位或同步");
if(intent==null||sessionToken.isEmpty()||!validIdentity()){stopSelf();return START_NOT_STICKY;}
String action=intent.getAction();
if("STOP".equals(action)){stopSharing();return START_NOT_STICKY;}
if("SYNC".equals(action)){forceSync=true;nextAttempt=0;notification(active?"位置共享中 · 正在补传轨迹":"只同步已采集轨迹,不开启定位");return START_NOT_STICKY;}
if("SYNC".equals(action)||"RETRY".equals(action)){
if("SYNC".equals(action))forceSync=true;
if(busy)return START_NOT_STICKY;
restore();bounded();worker.execute(this::cycle);return START_NOT_STICKY;
}
if("SAMPLE".equals(action)||"REPORT".equals(action)){
if(prefs.getLong("expires",0)<=System.currentTimeMillis()){prefs.edit().putBoolean("active",false).putBoolean("stopPending",true).apply();LocationSchedule.cancelSampling(this);LocationSchedule.retry(this,10000);if(!busy)stopSelf();return START_NOT_STICKY;}
if(!LocationSchedule.enabled(prefs)||!prefs.getString("sessionNonce","").equals(intent.getStringExtra("session"))){if(!busy)stopSelf();return START_NOT_STICKY;}
if(busy)return START_NOT_STICKY;
restore();bounded();
if("SAMPLE".equals(action))listen();else worker.execute(this::cycle);
return START_NOT_STICKY;
}
if(active||stopping||starting)return START_NOT_STICKY;
starting=true;busy=true;notification("正在确认本人的共享授权");
starting=true;busy=true;bounded();
worker.execute(()->{try{
JSONObject result=DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","start").put("consent",true).put("receipt",prefs.getString("receipt","")).put("bufferedHistory",true));
if(stopping||destroyed)return;
if(stopping||!validIdentity())return;
intervalSeconds=LocationCadence.seconds(result.optInt("intervalSeconds",300));sampleSeconds=LocationCadence.sample(result.optInt("sampleIntervalSeconds",60));
collection=result.optString("collectionId");historyEnabled=result.optBoolean("historyEnabled",false)&&!collection.isEmpty();
realtime="realtime".equals(result.optString("sharingMode","scheduled"));collection=result.optString("collectionId");historyEnabled=result.optBoolean("historyEnabled",false)&&!collection.isEmpty();
collectionStarted=(long)(result.optDouble("collectionStartedAt",System.currentTimeMillis()/1000d)*1000);
active=true;starting=false;sentFix=false;lastUpload=0;lastSample=0;forceSync=true;
prefs.edit().putBoolean("active",true).putLong("lastFlushAt",System.currentTimeMillis()).putLong("expires",(long)(result.getDouble("expires")*1000)).putString("status","共享中,等待定位").apply();
ui.post(()->{if(!stopping&&!destroyed){listen();notification("共享给 "+prefs.getString("recipients","")+" · 可随时停止");}});
}catch(Exception e){starting=false;busy=false;if(!destroyed){prefs.edit().putBoolean("active",false).putString("status","未开启:请检查网络、配对有效期").apply();stopSelf();}}});
active=true;starting=false;long now=System.currentTimeMillis();queue.clearLatest(owner);
prefs.edit().putBoolean("active",true).putBoolean("stopPending",false).putString("sharingMode",realtime?"realtime":"scheduled")
.putString("sessionToken",sessionToken).putString("sessionNonce",LocationQueue.id()).putString("collectionId",collection).putBoolean("collectHistory",historyEnabled).putLong("collectionStarted",collectionStarted)
.putLong("nextSampleAt",now).putLong("nextReportAt",now).putLong("lastLiveAt",0).putLong("flushCutoff",0).putLong("expires",(long)(result.getDouble("expires")*1000)).putString("status","共享已开启,等待本次定位").apply();
ui.post(()->{if(stopping||!validIdentity())return;if(realtime){ui.removeCallbacks(workTimeout);if(wake!=null&&wake.isHeld())wake.release();worker.scheduleWithFixedDelay(this::cycle,10,10,TimeUnit.SECONDS);}listen();});
}catch(Exception e){starting=false;busy=false;if(validIdentity()){prefs.edit().putBoolean("active",false).putString("status","未开启:请检查网络、配对有效期").apply();ui.post(this::finishWork);}}});
return START_NOT_STICKY;
}
void listen(){
if(!active||stopping)return;
try{for(String provider:new String[]{LocationManager.GPS_PROVIDER,LocationManager.NETWORK_PROVIDER})if(manager.getAllProviders().contains(provider))manager.requestLocationUpdates(provider,sampleSeconds*1000L,0,this);}
catch(SecurityException e){prefs.edit().putString("status","定位权限未开启").apply();}
void restore(){
active=LocationSchedule.enabled(prefs);realtime=false;busy=true;
intervalSeconds=LocationCadence.seconds(prefs.getInt("intervalSeconds",300));sampleSeconds=LocationCadence.sample(prefs.getInt("sampleIntervalSeconds",60));
collection=prefs.getString("collectionId","");collectionStarted=prefs.getLong("collectionStarted",0);historyEnabled=prefs.getBoolean("collectHistory",false)&&!collection.isEmpty();
stopping=prefs.getBoolean("stopPending",false);
}
boolean connected(){try{Network network=connectivity.getActiveNetwork();NetworkCapabilities caps=connectivity.getNetworkCapabilities(network);return !networkBlocked&&caps!=null&&caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);}catch(Exception e){return false;}}
void tick(){
void listen(){
if(!active||stopping||!validIdentity())return;
if(!realtime&&Build.VERSION.SDK_INT>=29&&checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)!=PackageManager.PERMISSION_GRANTED){prefs.edit().putString("status","定时采集需要始终允许定位,请在我的设置中检查").apply();finishCapture(null);return;}
capturing=true;captureStarted=System.currentTimeMillis();notification(realtime?"实时定位与共享中 · 可随时停止":"短暂采集当前位置 · 完成后释放定位");
try{for(String provider:new String[]{LocationManager.GPS_PROVIDER,LocationManager.NETWORK_PROVIDER})if(manager.getAllProviders().contains(provider))manager.requestLocationUpdates(provider,realtime?10000L:0,0,this);}
catch(SecurityException e){finishCapture("定位权限未开启");return;}
if(!realtime)ui.postDelayed(captureTimeout,30000);
}
void detach(){capturing=false;ui.removeCallbacks(captureTimeout);try{manager.removeUpdates(this);}catch(Exception ignored){}}
void finishCapture(String message){
detach();if(message!=null)prefs.edit().putString("status",message).apply();
if(!realtime&&active){long next=System.currentTimeMillis()+sampleSeconds*1000L;prefs.edit().putLong("nextSampleAt",next).apply();LocationSchedule.arm(this,LocationSchedule.SAMPLE,next);}
if(!destroyed)worker.execute(this::cycle);
}
boolean connected(){try{NetworkCapabilities c=connectivity.getNetworkCapabilities(connectivity.getActiveNetwork());return !networkBlocked&&c!=null&&c.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);}catch(Exception e){return false;}}
void cycle(){
if(destroyed||starting)return;
boolean reportRequested=false;
try{
if(!validIdentity())return;
if(active&&System.currentTimeMillis()>prefs.getLong("expires",0)){ui.post(this::stopSharing);return;}
updateQueueStatus();
if(!active&&!stopping&&queue.stats(owner)[0]==0){stopSelf();return;}
if(!connected()){failedNetwork=true;prefs.edit().putString("syncStatus","网络不可用,已采集轨迹加密保留在本机,恢复后自动补传").apply();return;}
if(SystemClock.elapsedRealtime()<nextAttempt)return;
updateQueueStatus();long now=System.currentTimeMillis();
boolean due=active&&now>=prefs.getLong("nextReportAt",0);
reportRequested=active&&(due||forceSync||prefs.getBoolean("reportPending",false));
if(!connected()){
prefs.edit().putString("syncStatus","网络不可用,已采集轨迹加密保留;联网后补传").apply();
if(due||forceSync||stopping||queue.hasBatches(owner)){prefs.edit().putBoolean("reportPending",true).apply();LocationSchedule.retry(this,10000);}return;
}
if(stopping){
try{DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","stop"));}catch(DisplayApi.ApiError e){if(e.status!=401&&e.status!=403)throw e;}
stopping=false;busy=false;prefs.edit().putString("status","共享关闭,平台已清除当前位置").apply();notification("正在补传关闭前已采集的轨迹");forceSync=true;
stopping=false;prefs.edit().putBoolean("stopPending",false).putString("status","共享已关闭,平台已清除当前位置").apply();forceSync=true;
}
if(active)uploadLive();
long now=System.currentTimeMillis();
if(forceSync||failedNetwork||active&&now-prefs.getLong("lastFlushAt",0)>=intervalSeconds*1000L){
flushCutoff=now;prefs.edit().putLong("lastFlushAt",now).apply();forceSync=false;
if(reportRequested){uploadLive();if(!validIdentity()||stopping)return;}
if(due||forceSync||prefs.getBoolean("reportPending",false)){
prefs.edit().putLong("flushCutoff",now).putLong("nextReportAt",now+intervalSeconds*1000L).putBoolean("reportPending",false).apply();forceSync=false;
}
for(int i=0;i<LocationQueue.MAX_INFLIGHT;i++){
LocationQueue.Batch batch=queue.next(owner,flushCutoff,now);if(batch==null)break;
JSONObject reply=DisplayApi.call("/api/location/update",sessionToken,batch.request());
if(destroyed)return;
reportRequested=false;
for(int i=0;i<LocationQueue.MAX_INFLIGHT&&validIdentity();i++){
if(!realtime&&SystemClock.elapsedRealtime()>deadline-20000)break;
LocationQueue.Batch batch=queue.next(owner,prefs.getLong("flushCutoff",0),now);if(batch==null)break;
JSONObject reply=DisplayApi.call("/api/location/update",sessionToken,batch.request());if(!validIdentity())return;
boolean removed=queue.acknowledge(owner,batch,reply);
prefs.edit().putString("syncStatus",removed?"网盘完整校验通过,已清理对应手机记录":"平台已接收,等待网盘回读校验;本机副本继续保留").apply();
if(removed)cacheFull=false;
prefs.edit().putString("syncStatus",removed?"网盘完整校验通过,已清理对应手机记录":"平台已接收,等待网盘回读校验;本机副本保留").apply();if(removed)cacheFull=false;
}
failures=0;nextAttempt=0;failedNetwork=false;updateQueueStatus();
}catch(DisplayApi.ApiError error){
if(error.status==401||error.status==403){
if(active)ui.post(this::stopSharing);
prefs.edit().putString("syncStatus","采集或配对授权已结束,未上传记录仍保留;请核对授权或手动清理").apply();nextAttempt=SystemClock.elapsedRealtime()+300000;
}else if(error.status==400||error.status==409){prefs.edit().putString("syncStatus","批次或授权校验未通过,本机记录保留,可手动重试或清理").apply();nextAttempt=SystemClock.elapsedRealtime()+300000;}
else retry("上传尚未完成,本机记录保留,稍后自动重试");
}catch(SecurityException error){prefs.edit().putString("syncStatus","回执校验未通过,手机轨迹没有删除").apply();nextAttempt=SystemClock.elapsedRealtime()+300000;}
catch(Exception error){retry("网络或同步暂未完成,手机轨迹已保留,恢复后自动补传");}
updateQueueStatus();if(queue.ready(owner,prefs.getLong("flushCutoff",0)))LocationSchedule.retry(this,30000);
}catch(DisplayApi.ApiError e){
if(reportRequested)prefs.edit().putBoolean("reportPending",true).apply();
if(e.status==401||e.status==403){active=false;realtime=false;LocationSchedule.cancelSampling(this);prefs.edit().putBoolean("active",false).putString("status","共享授权已结束,请检查配对与授权").apply();ui.post(this::detach);}
prefs.edit().putString("syncStatus","同步未完成,本机记录保留,可检查网络或授权后重试").apply();if(e.status!=401&&e.status!=403)LocationSchedule.retry(this,60000);
}catch(Exception e){if(reportRequested)prefs.edit().putBoolean("reportPending",true).apply();prefs.edit().putString("syncStatus","同步或回执校验未完成,本机记录保留,稍后重试").apply();LocationSchedule.retry(this,60000);}
finally{if(!realtime&&!capturing&&!starting)ui.post(this::finishWork);}
}
void retry(String message){failedNetwork=true;failures=Math.min(failures+1,5);nextAttempt=SystemClock.elapsedRealtime()+Math.min(300000,10000L*(1L<<failures));prefs.edit().putString("syncStatus",message).apply();}
void uploadLive()throws Exception{
long now=System.currentTimeMillis();if(now-prefs.getLong("lastLiveAt",0)<10000)return;
String signal=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED?locationEnabled(manager)?"waiting":"location_disabled":"permission_denied";
boolean safetyChange=!"waiting".equals(signal)&&!signal.equals(lastSignal);
if(!LocationCadence.due(SystemClock.elapsedRealtime(),lastUpload,intervalSeconds,safetyChange||latest!=null&&!sentFix))return;
JSONObject body=new JSONObject().put("action","update").put("bufferedHistory",true);Location fix=latest;
if(fix!=null&&"waiting".equals(signal)&&SystemClock.elapsedRealtimeNanos()-fix.getElapsedRealtimeNanos()<900000000000L){body.put("position",position(fix));signal="available";}
body.put("signal",signal);DisplayApi.call("/api/location/update",sessionToken,body);lastUpload=SystemClock.elapsedRealtime();lastSignal=signal;if("available".equals(signal))sentFix=true;
if(!stopping&&!destroyed)prefs.edit().putString("status","available".equals(signal)?"共享中 · 最近上传 "+java.text.DateFormat.getTimeInstance().format(new java.util.Date()):"共享中 · 等待定位,请检查手机定位和权限").apply();
}
static JSONObject position(Location fix)throws Exception{return new JSONObject().put("latitude",fix.getLatitude()).put("longitude",fix.getLongitude()).put("accuracy",fix.getAccuracy()).put("at",fix.getTime()/1000d);}
void updateQueueStatus(){long[] stats=queue.stats(owner);prefs.edit().putLong("pendingPoints",stats[0]).putLong("pendingBytes",stats[1]).putLong("uploadedPoints",stats[2]).putLong("freedBytes",stats[3]).putBoolean("cacheFull",cacheFull).apply();}
static boolean locationEnabled(LocationManager manager){return Build.VERSION.SDK_INT>=28?manager.isLocationEnabled():manager.isProviderEnabled(LocationManager.GPS_PROVIDER)||manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}
void stopSharing(){
if(stopping)return;stopping=true;starting=false;busy=true;active=false;latest=null;
try{manager.removeUpdates(this);}catch(Exception ignored){}
prefs.edit().putBoolean("active",false).putString("status","本机已停止采集,联网后通知平台清除当前位置;关闭前轨迹仍会补传").apply();notification("已停止定位 · 联网后完成同步");nextAttempt=0;
JSONObject body=new JSONObject().put("action","update").put("bufferedHistory",true),fix=queue.latest(owner);
if(fix!=null&&"waiting".equals(signal)&&now-fix.optDouble("at")*1000<900000){body.put("position",fix);signal="available";}
body.put("signal",signal);DisplayApi.call("/api/location/update",sessionToken,body);
if(validIdentity()&&!stopping)prefs.edit().putLong("lastLiveAt",now).putString("status",(realtime?"实时共享中":"定时共享中")+" · 最近汇报 "+java.text.DateFormat.getTimeInstance().format(new java.util.Date(now))).apply();
}
public void onLocationChanged(Location value){
if(!active||stopping)return;
Location fix=new Location(value);long elapsed=fix.getElapsedRealtimeNanos()/1000000;
if(!LocationCadence.sampleDue(elapsed,lastSample,sampleSeconds)||fix.getTime()<collectionStarted-5000||fix.getTime()>System.currentTimeMillis()+60000||System.currentTimeMillis()-fix.getTime()>900000)return;
lastSample=elapsed;latest=fix;if(!historyEnabled)return;
String session=collection;long epoch=prefs.getLong("queueEpoch",0);
recorder.execute(()->{try{
if(epoch!=prefs.getLong("queueEpoch",0))return;
if(queue.append(owner,session,position(fix))){cacheFull=false;}
else{cacheFull=true;prefs.edit().putString("syncStatus","本地缓存已达上限,暂停新增历史;未上传记录没有覆盖,请联网补传").apply();notification("轨迹缓存已满 · 请联网补传");}
if(!active||!capturing||stopping||!validIdentity())return;
Location fix=new Location(value);long elapsed=fix.getElapsedRealtimeNanos()/1000000,now=System.currentTimeMillis();
if(!LocationCadence.sampleDue(elapsed,lastSample,realtime?10:sampleSeconds)||fix.getTime()<Math.max(collectionStarted-5000,captureStarted-5000)||fix.getTime()>now+60000||now-fix.getTime()>900000)return;
lastSample=elapsed;if(!realtime)detach();long epoch=prefs.getLong("queueEpoch",0);
worker.execute(()->{try{
if(!validIdentity()||epoch!=prefs.getLong("queueEpoch",0)||!prefs.getBoolean("active",false))return;
queue.latest(owner,position(fix));
if(historyEnabled){cacheFull=!queue.append(owner,collection,position(fix));if(cacheFull)prefs.edit().putString("syncStatus","缓存已达上限,暂停新增历史;未上传记录保留").apply();}
updateQueueStatus();
}catch(Exception error){cacheFull=true;prefs.edit().putString("syncStatus","本地轨迹未能写入,请检查手机存储空间;已有记录保留").apply();}});
}catch(Exception e){prefs.edit().putString("syncStatus","本次定位未能写入,请检查手机空间;已有记录保留").apply();}
finally{if(!realtime&&!destroyed&&!stopping&&active)ui.post(()->finishCapture("定时共享中 · 本次采集结束,定位已释放"));}});
}
public void onStatusChanged(String provider,int status,Bundle extras){}
public void onProviderEnabled(String provider){}
public void onProviderDisabled(String provider){}
public IBinder onBind(Intent intent){return null;}
void stopSharing(){
LocationSchedule.cancelSampling(this);active=false;realtime=false;stopping=true;starting=false;busy=true;detach();
prefs.edit().putBoolean("active",false).putBoolean("stopPending",true).putString("sessionNonce",LocationQueue.id()).putString("status","本机已停止采集;联网后清除平台当前位置").apply();
bounded();notification("已停止定位 · 正在同步关闭状态");worker.execute(()->{queue.clearLatest(owner);cycle();});
}
void finishWork(){
if(finishing||destroyed)return;finishing=true;detach();ui.removeCallbacks(workTimeout);
if(LocationSchedule.enabled(prefs)){
long now=System.currentTimeMillis();if(prefs.getLong("nextSampleAt",0)<=now)prefs.edit().putLong("nextSampleAt",now+sampleSeconds*1000L).apply();if(prefs.getLong("nextReportAt",0)<=now)prefs.edit().putLong("nextReportAt",now+intervalSeconds*1000L).apply();
LocationSchedule.resume(this);
}
if(wake!=null&&wake.isHeld())wake.release();stopForeground(true);stopSelf();
}
static JSONObject position(Location f)throws Exception{return new JSONObject().put("latitude",f.getLatitude()).put("longitude",f.getLongitude()).put("accuracy",f.getAccuracy()).put("at",f.getTime()/1000d);}
void updateQueueStatus(){long[] v=queue.stats(owner);prefs.edit().putLong("pendingPoints",v[0]).putLong("pendingBytes",v[1]).putLong("uploadedPoints",v[2]).putLong("freedBytes",v[3]).putBoolean("cacheFull",cacheFull).apply();}
static boolean locationEnabled(LocationManager m){return Build.VERSION.SDK_INT>=28?m.isLocationEnabled():m.isProviderEnabled(LocationManager.GPS_PROVIDER)||m.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}
public void onStatusChanged(String p,int s,Bundle b){}public void onProviderEnabled(String p){}public void onProviderDisabled(String p){}
public IBinder onBind(Intent i){return null;}
public void onDestroy(){
destroyed=true;active=false;latest=null;try{manager.removeUpdates(this);}catch(Exception ignored){}try{connectivity.unregisterNetworkCallback(networkCallback);}catch(Exception ignored){}
if(worker!=null)worker.shutdownNow();if(recorder!=null)recorder.shutdown();prefs.edit().putBoolean("active",false).apply();busy=false;stopForeground(true);super.onDestroy();
destroyed=true;detach();ui.removeCallbacksAndMessages(null);try{connectivity.unregisterNetworkCallback(networkCallback);}catch(Exception ignored){}
if(worker!=null)worker.shutdownNow();if(wake!=null&&wake.isHeld())wake.release();
if(realtime)prefs.edit().putBoolean("active",false).putBoolean("stopPending",true).putString("status","实时共享已中断,请本人重新开启").apply();
busy=false;stopForeground(true);super.onDestroy();
}
}
@@ -0,0 +1,12 @@
package cn.ucvl.zhaodisplay;
import android.app.job.*;
import android.content.*;
/** A network-constrained retry starts bounded data sync only; never enables GPS. */
public class LocationSyncJob extends JobService {
public boolean onStartJob(JobParameters params){
if(!params.getExtras().getString("token","").equals(getSharedPreferences("location",0).getString("token","")))return false;
try{startForegroundService(new Intent(this,LocationService.class).setAction("RETRY"));}catch(Exception e){LocationSchedule.retry(this,300000);}
return false;
}
public boolean onStopJob(JobParameters params){return true;}
}
@@ -39,7 +39,7 @@ final class PhoneLayout extends LinearLayout {
shareCard=s.column();s.card(shareCard);mineContent.addView(shareCard);sharing=new Switch(app);sharing.setText("共享我的位置");sharing.setTextSize(19);sharing.setTypeface(null,Typeface.BOLD);sharing.setTextColor(PhoneStyle.INK);sharing.setMinHeight(s.dp(50));sharing.setThumbTintList(new android.content.res.ColorStateList(new int[][]{new int[]{android.R.attr.state_checked},new int[]{}},new int[]{PhoneStyle.GREEN,0xffb5bcb6}));shareCard.addView(sharing);
LinearLayout state=s.line();state.setPadding(s.dp(10),s.dp(6),s.dp(4),s.dp(6));state.setBackground(s.shape(0xfffff4de,12));myStatus=s.label("共享关闭",13,0xff805c23);state.addView(myStatus,new LayoutParams(0,-2,1));myCheck=s.button("检查权限",false);state.addView(myCheck);shareCard.addView(state);s.gap(shareCard,10);shareCard.addView(s.label("查看家人位置,无需开启自己的共享。",12,PhoneStyle.MUTED));
section(mineContent,"允许谁查看");LinearLayout access=s.column();s.card(access);mineContent.addView(access);viewers=s.row("family","查看人名单","读取中");access.addView(viewers);expiry=s.row("clock","共享有效期","跟随本机配对有效期");access.addView(expiry);
section(mineContent,"定位与轨迹");LinearLayout location=s.column();s.card(location);mineContent.addView(location);sampling=s.row("location","定位采集频率","每 1 分钟");upload=s.row("cloud","集中上传周期","每 5 分钟");history=s.row("track","我的历史轨迹","每天、每周、每月、每年、一生");permissions=s.row("shield","定位权限与系统设置","本人开启共享后才采集");for(View row:new View[]{sampling,upload,history,permissions})location.addView(row);
section(mineContent,"定位与轨迹");LinearLayout location=s.column();s.card(location);mineContent.addView(location);sampling=s.row("location","共享模式与采集频率","定时采集 · 每 1 分钟");upload=s.row("cloud","集中上传周期","每 5 分钟");history=s.row("track","我的历史轨迹","每天、每周、每月、每年、一生");permissions=s.row("shield","定位权限与系统设置","本人开启共享后才采集");for(View row:new View[]{sampling,upload,history,permissions})location.addView(row);
section(mineContent,"沟通与声音");voiceSettings=s.column();s.card(voiceSettings);mineContent.addView(voiceSettings);
section(pages[2],"设备与系统");LinearLayout device=s.column();s.card(device);pages[2].addView(device);pairing=s.row("phone","配对与设备","查看或更换手机配对");device.addView(pairing);
nav=s.line();nav.setBackgroundColor(PhoneStyle.CARD);nav.setPadding(s.dp(8),s.dp(4),s.dp(8),s.dp(6));addView(nav,new LayoutParams(-1,-2));String[] names={"位置","沟通","我的"},icons={"location","mic","person"};
@@ -11,7 +11,14 @@ import java.util.function.Consumer;
final class VoiceChat extends LinearLayout {
final PhoneStyle s;final LinearLayout messages;final TextView notice,heading;final Button older,latest;final ScrollView scroll;
boolean night=false,savedMore=false,savedPast=false;JSONArray saved=new JSONArray();
String signature="";Consumer<String> replay=id->{};
String signature="";Consumer<String> replay=id->{};LinearLayout transfer;
void transfer(String description,boolean failed,Runnable retry,Runnable discard){
if(transfer!=null){messages.removeView(transfer);transfer=null;}if(description.isEmpty())return;
transfer=s.column();transfer.setPadding(s.dp(12),s.dp(10),s.dp(12),s.dp(10));transfer.setBackground(s.shape(PhoneStyle.PALE,14));
transfer.addView(s.label(description,13,PhoneStyle.INK));
if(failed){LinearLayout actions=s.line();Button again=s.button("重试发送",true),cancel=s.button("放弃本次",false);actions.addView(again);actions.addView(cancel);again.setOnClickListener(v->retry.run());cancel.setOnClickListener(v->discard.run());transfer.addView(actions);}
messages.addView(transfer);scroll.post(()->scroll.fullScroll(FOCUS_DOWN));
}
VoiceChat(Activity app){
super(app);s=new PhoneStyle(app);setOrientation(VERTICAL);s.card(this);
LinearLayout head=s.line();heading=s.bold("聊天记录",18);head.addView(heading,new LayoutParams(0,-2,1));older=s.button("更早",false);latest=s.button("最近",false);head.addView(older);head.addView(latest);addView(head);
@@ -23,7 +30,7 @@ final class VoiceChat extends LinearLayout {
void clear(String text){signature="";saved=new JSONArray();messages.removeAllViews();notice.setText(text);older.setEnabled(false);}
void theme(boolean value){if(night==value)return;night=value;setBackground(s.shape(night?0xff21372d:PhoneStyle.CARD,20));heading.setTextColor(night?0xffc8d5cd:PhoneStyle.INK);notice.setTextColor(night?0xff96aaa0:PhoneStyle.MUTED);for(Button b:new Button[]{older,latest}){b.setTextColor(night?0xffc8d5cd:PhoneStyle.GREEN);b.setBackground(s.shape(night?0xff2d4439:PhoneStyle.PALE,14));}if(saved.length()>0){signature="";show(saved,savedMore,savedPast,replay);}}
void show(JSONArray items,boolean hasMore,boolean past,Consumer<String> play){
replay=play;saved=items;savedMore=hasMore;savedPast=past;older.setEnabled(hasMore);notice.setText(past?"较早的记录 · 可继续向前翻阅":"长期保留 · 点击语音回听");
replay=play;saved=items;savedMore=hasMore;savedPast=past;older.setEnabled(hasMore);notice.setText(past?"较早的 10 条 · 可继续向前翻阅":"最近 10 条 · 点语音回听 · 更早记录按需加载");
String next=items.toString();if(next.equals(signature))return;boolean follow=signature.isEmpty()||scroll.getScrollY()+scroll.getHeight()>=messages.getHeight()-s.dp(32);int oldScroll=scroll.getScrollY();signature=next;messages.removeAllViews();
if(items.length()==0){TextView empty=s.label("还没有聊天记录\n按住下方按钮,给家人说句话吧",15,PhoneStyle.MUTED);empty.setGravity(Gravity.CENTER);empty.setPadding(0,s.dp(42),0,s.dp(30));messages.addView(empty);return;}
for(int i=0;i<items.length();i++){
@@ -34,8 +41,10 @@ final class VoiceChat extends LinearLayout {
row.addView(s.label(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA).format(new Date((long)(item.optDouble("at")*1000))),11,muted));
Button voice=s.button("▶ 语音 · "+String.format(Locale.CHINA,"%.1f",item.optDouble("seconds"))+" 秒",mine);if(night){voice.setTextColor(ink);voice.setBackground(s.shape(0xff355549,14));}voice.setContentDescription("播放 "+name+" 的语音");voice.setOnClickListener(v->replay.accept(item.optString("id")));row.addView(voice,new LayoutParams(-1,-2));
String delivery=item.optString("delivery"),archive=item.optString("archive");
String state=delivery.equals("played")?"已播放":delivery.equals("received")?"已送达":delivery.equals("queued")?"等待播放":"未自动播放 · 可以回听";
row.addView(s.label(state+" · "+(archive.equals("cloud")?"已存网盘":archive.equals("retry")?"网盘归档重试中":"网盘归档中"),11,muted));
String state=delivery.equals("played")?"已送达 · 已播放":delivery.equals("received")?"已送达 · 尚未完整播放":delivery.equals("queued")?"已发送 · 等待送达":delivery.equals("rejected")?"未完整播放 · 可回听":"自动播放已过期 · 可回听";
if(delivery.equals("transferring"))state="传输中 · 等待对方确认接收";
row.addView(s.label(state,12,muted));
row.addView(s.label(archive.equals("cloud")?"✓ 已存网盘 · 校验完成":archive.equals("retry")?"网盘归档待重试 · 临时副本保留":archive.equals("uploading")?"↑ 正在传输到网盘":"等待存入网盘",11,muted));
}
if(!past&&follow)scroll.post(()->scroll.fullScroll(FOCUS_DOWN));else scroll.post(()->scroll.scrollTo(0,past?0:oldScroll));
}
@@ -20,6 +20,7 @@ final class VoicePanel extends LinearLayout {
final Activity app;final String kind;final Supplier<String> token;
final Handler ui=new Handler();final ExecutorService worker=Executors.newSingleThreadExecutor();
final TextView status;final Button speak,settings,stop;final VoiceSurface dock;VoiceSurface expanded,page;Dialog sheet;
byte[] pendingAudio;String pendingToken="",pendingTarget="",pendingId="",pendingPeer="",pendingName="";long pendingAt=0;double pendingSeconds=0;boolean pendingFailed=false;
String selectedId="";boolean networkReady=false;long feedbackAt=0;
boolean communicationVisible=false,historyLoading=false,historyPlayback=false;long historyBefore=0,nextBefore=0;int historyEpoch=0,playbackRequest=0;String historyPeer="";
final AudioManager audio;final AudioAttributes attributes=new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build();
@@ -38,8 +39,8 @@ final class VoicePanel extends LinearLayout {
}
void showStatus(String text){VoiceSurface.text(status,text);feedbackAt=SystemClock.elapsedRealtime();if(expanded!=null)VoiceSurface.text(expanded.status,text);if(page!=null)VoiceSurface.text(page.status,text);}
VoiceSurface page(){if(page==null){page=new VoiceSurface(app,true);page.communicationPage();wire(page);page.expand.setVisibility(GONE);page.applyTheme(night);}renderSurfaces();return page;}
void communication(boolean value){communicationVisible=value;if(value)loadConversation(false);}
void chooseTarget(){if(recorder!=null||sending)return;if(destinations==null||destinations.length()==0){new AlertDialog.Builder(app).setTitle("暂无可接收的家人").setMessage("请对方打开 App,在接收设置中允许你向其喊话。显示终端也需要先授权。").setPositiveButton("知道了",null).show();return;}String[] names=new String[destinations.length()];int selected=-1;for(int i=0;i<names.length;i++){JSONObject d=destinations.optJSONObject(i);names[i]=d.optString("name")+" · "+(d.optBoolean("online")?"在线":"未打开 App");if(d.optString("id").equals(selectedId))selected=i;}final JSONArray snapshot=destinations;new AlertDialog.Builder(app).setTitle("发给谁").setSingleChoiceItems(names,selected,(d,i)->{choose(snapshot.optJSONObject(i).optString("id"));d.dismiss();}).setNegativeButton("取消",null).show();}
void communication(boolean value){communicationVisible=value;if(value){loadConversation(false);renderTransfer();}}
void chooseTarget(){if(recorder!=null||sending||pendingAudio!=null){if(pendingAudio!=null)showStatus("请先重试或放弃本次待发送语音");return;}if(destinations==null||destinations.length()==0){new AlertDialog.Builder(app).setTitle("暂无可接收的家人").setMessage("请对方打开 App,在接收设置中允许你向其喊话。显示终端也需要先授权。").setPositiveButton("知道了",null).show();return;}String[] names=new String[destinations.length()];int selected=-1;for(int i=0;i<names.length;i++){JSONObject d=destinations.optJSONObject(i);names[i]=d.optString("name")+" · "+(d.optBoolean("online")?"在线":"未打开 App");if(d.optString("id").equals(selectedId))selected=i;}final JSONArray snapshot=destinations;new AlertDialog.Builder(app).setTitle("发给谁").setSingleChoiceItems(names,selected,(d,i)->{choose(snapshot.optJSONObject(i).optString("id"));d.dismiss();}).setNegativeButton("取消",null).show();}
void wire(VoiceSurface view){
view.chat.older.setOnClickListener(v->{if(!historyLoading&&nextBefore>0){historyBefore=nextBefore;loadConversation(true);}});
view.chat.latest.setOnClickListener(v->{if(!historyLoading){historyBefore=0;loadConversation(true);}});
@@ -73,7 +74,7 @@ final class VoicePanel extends LinearLayout {
void choose(String id){if(recorder!=null||sending)return;stopPlayer("rejected");selectedId=id;lastMessage="";clearHistory("正在读取聊天记录…");JSONObject d=destination();showStatus(d!=null&&d.optBoolean("online")?"按住说话,松开发送给 "+d.optString("name"):"可以回听历史;发送需要对方授权并在线");renderSurfaces();loadConversation(true);}
void renderSurfaces(){
JSONObject selected=destination();String name=selected==null?"":selected.optString("name");boolean available=selected!=null&&selected.optBoolean("online");
boolean can=networkReady&&available&&selected.optBoolean("canSend",true)&&!sending&&microphone();int amplitude=0;if(recorder!=null)try{amplitude=recorder.getMaxAmplitude();}catch(Exception ignored){}
boolean can=networkReady&&available&&selected.optBoolean("canSend",true)&&!sending&&pendingAudio==null&&microphone();int amplitude=0;if(recorder!=null)try{amplitude=recorder.getMaxAmplitude();}catch(Exception ignored){}
for(VoiceSurface view:new VoiceSurface[]{dock,expanded,page}){if(view==null)continue;
if(recorder==null||view.full)VoiceSurface.text(view.recipient,name.isEmpty()?"选择一位家人":view.full?name:name+" · "+(available?"已打开 App":"未打开 App")+" ›");view.destination(selected,networkReady);view.receiving(enabled,networkReady&&recorder==null&&!sending);
VoiceSurface.text(view.receive,enabled?"● 接收已开启 · 仅限你允许的家人":"○ 接收已关闭 · 可在接收设置中开启");
@@ -89,8 +90,8 @@ final class VoicePanel extends LinearLayout {
if(closed)return;visible=value;epoch++;ui.removeCallbacks(refresh);ui.removeCallbacks(visual);
if(value){ui.post(refresh);ui.post(visual);}else{clearHistory("打开沟通后读取记录");if(sheet!=null)sheet.dismiss();finish(false);stopPlayer("rejected");String t=token.get();if(!t.isEmpty())worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("offline"));}catch(Exception ignored){}});}
}
void rebound(){active(false);choices=new JSONArray();allowed=new JSONArray();destinations=new JSONArray();enabled=false;networkReady=false;selectedId="";lastMessage="";active(true);}
void close(){active(false);closed=true;ui.removeCallbacksAndMessages(null);worker.shutdown();}
void rebound(){active(false);pendingAudio=null;choices=new JSONArray();allowed=new JSONArray();destinations=new JSONArray();enabled=false;networkReady=false;selectedId="";lastMessage="";active(true);}
void close(){active(false);pendingAudio=null;closed=true;ui.removeCallbacksAndMessages(null);worker.shutdown();}
void poll(){
if(polling||closed||!visible)return;
String t=token.get();if(t.isEmpty()){speak.setEnabled(false);settings.setEnabled(false);return;}final int e=epoch;polling=true;
@@ -124,7 +125,9 @@ final class VoicePanel extends LinearLayout {
for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null){view.chat.older.setEnabled(false);view.chat.latest.setEnabled(false);}
worker.execute(()->{try{
JSONObject result=DisplayApi.call("/api/voice",t,body("history").put("peer",peer).put("before",before));
ui.post(()->{if(!current(e,t)||request!=historyEpoch||!peer.equals(historyPeer))return;nextBefore=result.optLong("before");JSONArray items=result.optJSONArray("items");for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null)view.chat.show(items==null?new JSONArray():items,nextBefore>0,before>0,this::replay);});
ui.post(()->{if(!current(e,t)||request!=historyEpoch||!peer.equals(historyPeer))return;nextBefore=result.optLong("before");JSONArray items=result.optJSONArray("items");
if(items!=null&&pendingAudio!=null&&pendingToken.equals(t)&&pendingPeer.equals(peer))for(int i=0;i<items.length();i++){JSONObject row=items.optJSONObject(i);if(row!=null&&row.optBoolean("mine")&&row.optString("id").endsWith(":"+pendingId)){pendingAudio=null;pendingFailed=false;lastMessage=row.optString("id");break;}}
for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null)view.chat.show(items==null?new JSONArray():items,nextBefore>0,before>0,this::replay);renderTransfer();});
}catch(Exception error){ui.post(()->{if(current(e,t)&&request==historyEpoch)for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null)view.chat.notice.setText("聊天记录未能刷新,点“最近”重试");});}
finally{ui.post(()->{if(request==historyEpoch){historyLoading=false;for(VoiceSurface view:new VoiceSurface[]{page,expanded})if(view!=null){view.chat.latest.setEnabled(true);view.chat.older.setEnabled(nextBefore>0);}}});}});
}
@@ -149,7 +152,7 @@ final class VoicePanel extends LinearLayout {
worker.execute(()->{try{DisplayApi.call("/api/voice",t,body("configure").put("enabled",receive).put("allowed",ids).put("consent",true));ui.post(()->{if(current(e,t)){lastMessage="";poll();}});}catch(Exception error){ui.post(()->{if(current(e,t))showStatus("接收设置保存失败,请检查网络后重试");});}});
}
void begin(){
if(!visible||!networkReady||recorder!=null||sending||selectedTarget().isEmpty())return;
if(!visible||!networkReady||recorder!=null||sending||pendingAudio!=null||selectedTarget().isEmpty())return;
JSONObject target=destination();if(target==null||!target.optBoolean("online")||!target.optBoolean("canSend",true)){showStatus("请先让对方授权并打开 App");return;}
if(!microphone()){showStatus("请先连接麦克风;仍可接收家人喊话");return;}
if(app.checkSelfPermission(Manifest.permission.RECORD_AUDIO)!=0){app.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},46);showStatus("授权麦克风后,再次按住说话");return;}
@@ -165,13 +168,27 @@ final class VoicePanel extends LinearLayout {
try{r.stop();}catch(Exception error){send=false;}finally{r.release();}
File file=recording;recording=null;settings.setEnabled(true);renderSurfaces();
if(!send||SystemClock.elapsedRealtime()-started<350||file==null){if(file!=null)file.delete();showStatus(send?"说话时间太短,请按住后再说一句":"已取消,这条语音没有发送");renderSurfaces();return;}
final String t=recordToken,destination=recordTarget;final int e=epoch;sending=true;speak.setEnabled(false);showStatus("正在发送喊话…");
try{pendingAudio=Files.readAllBytes(file.toPath());if(pendingAudio.length>150000)throw new IOException("Too large");
pendingToken=recordToken;pendingTarget=recordTarget;pendingId=UUID.randomUUID().toString().replace("-","");pendingAt=System.currentTimeMillis();pendingSeconds=(SystemClock.elapsedRealtime()-started)/1000d;
JSONObject target=destination();pendingPeer=target==null?"":target.optString("archiveKey");pendingName=target==null?"对方":target.optString("name");pendingFailed=false;
}catch(Exception error){pendingAudio=null;showStatus("录音未能读取,请重新录制");}finally{file.delete();}
if(pendingAudio!=null)sendPending();
}
void renderTransfer(){
String text=pendingAudio==null||historyBefore>0||!pendingPeer.equals(historyPeer)?"":"我 → "+pendingName+" · "+String.format(Locale.CHINA,"%.1f 秒",pendingSeconds)+"\\n"+new java.text.SimpleDateFormat("HH:mm:ss",Locale.CHINA).format(new Date(pendingAt))+" · "+(pendingFailed?"发送未确认 · 可重试,不会重复发送\n本次临时保留,退出 App 后需重新录制":"↑ 正在传输 · 尚未确认送达");
for(VoiceSurface v:new VoiceSurface[]{page,expanded})if(v!=null)v.chat.transfer(text,pendingFailed,this::sendPending,()->{if(sending)return;pendingAudio=null;showStatus("已放弃本机待发送副本;如果服务器已收到,记录仍保留");renderTransfer();renderSurfaces();});
}
void sendPending(){
if(pendingAudio==null||sending||closed||!visible)return;
if(!pendingToken.equals(token.get())){pendingAudio=null;renderTransfer();return;}
final String t=pendingToken,target=pendingTarget,id=pendingId;final byte[] bytes=pendingAudio;final int e=epoch;
sending=true;pendingFailed=false;historyBefore=0;showStatus("正在传输语音…");renderTransfer();renderSurfaces();
worker.execute(()->{try{
if(!current(e,t))return;byte[] bytes=Files.readAllBytes(file.toPath());if(bytes.length>150000)throw new IOException("Too large");
JSONObject result=DisplayApi.call("/api/voice",t,body("send").put("target",destination).put("id",UUID.randomUUID().toString().replace("-","")).put("audio",Base64.encodeToString(bytes,Base64.NO_WRAP)));
ui.post(()->{if(current(e,t)){lastMessage=result.optString("id");showStatus("已发送,等待对方播放");}});
}catch(Exception error){ui.post(()->{if(current(e,t))showStatus("未发送,请检查网络或对方的接收权限后重新录制");});}
finally{file.delete();ui.post(()->{sending=false;if(current(e,t))poll();});}});
JSONObject result=DisplayApi.call("/api/voice",t,body("send").put("target",target).put("id",id).put("audio",Base64.encodeToString(bytes,Base64.NO_WRAP)));
ui.post(()->{if(t.equals(token.get())&&id.equals(pendingId)){pendingAudio=null;lastMessage=result.optString("id");if(current(e,t))showStatus("已发送,等待对方接收;网盘归档单独显示");}});
}catch(Exception error){ui.post(()->{if(t.equals(token.get())&&id.equals(pendingId)){pendingFailed=true;if(current(e,t))showStatus("发送结果未确认,请检查连接或权限后重试");}});}
finally{ui.post(()->{sending=false;if(!closed){renderTransfer();renderSurfaces();if(visible)poll();}});}
});
}
void take(String id){
// Reserve the playback slot while the download is in flight.
@@ -183,6 +200,7 @@ final class VoicePanel extends LinearLayout {
}
void play(JSONObject clip,String t,byte[] bytes){
try{
if(!historyPlayback)ack(t,clip.getString("id"),"received");
playingToken=t;focus=new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT).setAudioAttributes(attributes).setOnAudioFocusChangeListener(change->{if(change<0)stopPlayer("rejected");}).build();
if(audio.requestAudioFocus(focus)!=AudioManager.AUDIOFOCUS_REQUEST_GRANTED)throw new IOException("Audio busy");
playing=File.createTempFile("voice-play-",".aac",app.getCacheDir());Files.write(playing.toPath(),bytes);player=new MediaPlayer();player.setAudioAttributes(attributes);player.setDataSource(playing.getAbsolutePath());
+4 -1
View File
@@ -19,7 +19,10 @@ $env:Path="$jdk\bin;$env:Path"
'@ | Set-Content -LiteralPath "$stage\AndroidManifest.xml" -Encoding utf8
& "$bt\aapt2.exe" link -o "$stage\unsigned.apk" -I $android --manifest "$stage\AndroidManifest.xml"
if($LASTEXITCODE){throw 'Test resource linking failed'}
$sources=@("$source\src\cn\ucvl\zhaodisplay\LocationActivity.java","$source\src\cn\ucvl\zhaodisplay\PhoneLayout.java","$source\src\cn\ucvl\zhaodisplay\PhoneStyle.java","$source\src\cn\ucvl\zhaodisplay\VoicePanel.java","$source\src\cn\ucvl\zhaodisplay\VoiceSurface.java","$source\src\cn\ucvl\zhaodisplay\VoiceChat.java","$source\src\cn\ucvl\zhaodisplay\VoiceGesture.java","$source\src\cn\ucvl\zhaodisplay\LocationCadence.java") + @((Get-ChildItem "$tests\phone-preview" -Filter "*.java").FullName)
$queueSource=Get-Content -LiteralPath "$source\src\cn\ucvl\zhaodisplay\LocationQueue.java" -Raw -Encoding UTF8
$queueSource=$queueSource.Replace('LocationQueue','StoredLocationQueue').Replace('location-outbox.db','storage-check.db')
[IO.File]::WriteAllText("$stage\StoredLocationQueue.java",$queueSource,(New-Object Text.UTF8Encoding($false)))
$sources=@("$stage\StoredLocationQueue.java","$source\src\cn\ucvl\zhaodisplay\LocationService.java","$source\src\cn\ucvl\zhaodisplay\LocationActivity.java","$source\src\cn\ucvl\zhaodisplay\PhoneLayout.java","$source\src\cn\ucvl\zhaodisplay\PhoneStyle.java","$source\src\cn\ucvl\zhaodisplay\VoicePanel.java","$source\src\cn\ucvl\zhaodisplay\VoiceSurface.java","$source\src\cn\ucvl\zhaodisplay\VoiceChat.java","$source\src\cn\ucvl\zhaodisplay\VoiceGesture.java","$source\src\cn\ucvl\zhaodisplay\LocationCadence.java") + @((Get-ChildItem "$tests\phone-preview" -Filter "*.java").FullName)
& "$jdk\bin\javac.exe" -encoding UTF-8 -source 8 -target 8 -cp $android -d "$stage\classes" @sources
if($LASTEXITCODE){throw 'Test Java compile failed'}
& "$jdk\bin\jar.exe" cf "$stage\classes.jar" -C "$stage\classes" .
@@ -10,6 +10,7 @@ final class DisplayApi {
if(action.equals("history")){boolean old=body.optLong("before")>0;JSONArray items=new JSONArray();for(int i=0;i<3;i++)items.put(new JSONObject().put("id","chat-"+i).put("seq",i+1).put("mine",i%2==0).put("senderName",i%2==0?"示例成员的手机":"家庭显示终端").put("at",1792387200+i*60-(old?86400:0)).put("seconds",i+3.6).put("delivery",i==2?"queued":"played").put("archive",i==2?"pending":"cloud"));return new JSONObject().put("items",items).put("before",old?0:12);}
return new JSONObject("{\"enabled\":false,\"allowed\":[],\"candidates\":[{\"id\":\"phone:demo\",\"name\":\"示例家人的手机\"}],\"targets\":[{\"id\":\"display:demo\",\"archiveKey\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}],\"conversations\":[],\"sent\":[],\"inbox\":[]}");
}
if(action.equals("update")||action.equals("stop"))return new JSONObject().put("ok",true);
if(action.equals("list")){JSONObject a=new JSONObject("{\"id\":\"a\",\"name\":\"家人甲(示例)\",\"status\":\"live\"}");a.put("position",new JSONObject().put("latitude",0).put("longitude",0).put("accuracy",25).put("at",System.currentTimeMillis()/1000-120));JSONObject b=new JSONObject("{\"id\":\"b\",\"name\":\"家人乙(示例)\",\"status\":\"scheduled\",\"scheduleReason\":\"sampling\"}");JSONObject c=new JSONObject().put("id","c").put("name","家人丙(示例)").put("position",new JSONObject().put("latitude",0).put("longitude",0).put("accuracy",10).put("at",System.currentTimeMillis()/1000));return new JSONObject().put("items",new JSONArray().put(b).put(a).put(c));}
if(action.equals("settings"))return new JSONObject("{\"receipt\":\"fixture\",\"intervalSeconds\":7200,\"sampleIntervalSeconds\":300,\"historyEnabled\":true,\"historyDefault\":true,\"viewerIds\":[],\"phoneIds\":[\"demo\"],\"displayIds\":[],\"viewers\":[],\"phones\":[{\"id\":\"demo\",\"name\":\"示例家人的手机\"}],\"displays\":[],\"history\":{\"pending\":0,\"archived\":2,\"deleting\":0}}");
throw new ApiError(403);
@@ -1,3 +1,13 @@
package cn.ucvl.zhaodisplay;
/** Test-only empty queue; never touches production storage. */
final class LocationQueue {LocationQueue(android.content.Context c){}static String digest(String s){return "fixture";}long[] stats(String owner){return new long[]{0,0,0,0};}long total(){return 0;}void discard(String owner){}}
import org.json.*;
/** In-memory synthetic queue only. Production encryption and batch checks have separate tests. */
final class LocationQueue {
static final int MAX_INFLIGHT=4;JSONObject remembered;int appended=0;
LocationQueue(android.content.Context c){}static String digest(String s){return "fixture";}static String id(){return java.util.UUID.randomUUID().toString();}
long[] stats(String owner){return new long[]{0,0,0,0};}long total(){return 0;}void discard(String owner){}
void latest(String owner,JSONObject f){remembered=f;}JSONObject latest(String owner){return remembered;}void clearLatest(String owner){remembered=null;}
boolean append(String owner,String session,JSONObject point){appended++;return true;}
boolean hasBatches(String owner){return false;}boolean ready(String owner,long cutoff){return false;}
static class Batch {JSONObject request(){return new JSONObject();}}Batch next(String owner,long cutoff,long now){return null;}
boolean acknowledge(String owner,Batch batch,JSONObject receipt){return false;}
}
@@ -0,0 +1,7 @@
package cn.ucvl.zhaodisplay;
final class LocationSchedule {
static final int SAMPLE=4501,REPORT=4502;
static boolean enabled(android.content.SharedPreferences p){return p.getBoolean("active",false)&&"scheduled".equals(p.getString("sharingMode","scheduled"))&&p.getString("token","").equals(p.getString("sessionToken",""))&&p.getLong("expires",0)>System.currentTimeMillis();}
static void cancel(android.content.Context c){}static void cancelSampling(android.content.Context c){}
static void resume(android.content.Context c){}static void arm(android.content.Context c,int id,long at){}static void retry(android.content.Context c,long delay){}
}
@@ -1,3 +1,60 @@
package cn.ucvl.zhaodisplay;
/** Test-only noncollecting service. There are no location or foreground-service permissions. */
public class LocationService extends android.app.Service {static boolean busy=false;static boolean locationEnabled(android.location.LocationManager m){return false;}public android.os.IBinder onBind(android.content.Intent i){return null;}}
import android.content.*;
import android.location.Location;
import android.os.*;
/** Runs production service control flow, with synthetic fixes and no network/GPS permission. */
final class LocationCycleChecks {
static class Probe extends LocationService {
int listens=0,finishes=0;boolean online=true;
Probe(Context c){attachBaseContext(c);onCreate();}
void notification(String s){}
void bounded(){deadline=SystemClock.elapsedRealtime()+90000;}
void listen(){listens++;capturing=true;captureStarted=System.currentTimeMillis();}
boolean connected(){return online;}
void finishWork(){finishes++;detach();}
void dispose(){destroyed=true;detach();ui.removeCallbacksAndMessages(null);worker.shutdownNow();busy=false;}
}
static void check(boolean value,String message){if(!value)throw new AssertionError(message);}
static void run(Context c,Runnable done){
SharedPreferences p=c.getSharedPreferences("location",0);long now=System.currentTimeMillis();
p.edit().putBoolean("active",true).putString("sharingMode","scheduled").putString("sessionToken","synthetic-token").putString("sessionNonce","test")
.putLong("collectionStarted",now-10000).putLong("expires",now+86400000).putInt("intervalSeconds",7200).putInt("sampleIntervalSeconds",300)
.putLong("nextReportAt",now+7200000).putBoolean("collectHistory",true).putString("collectionId","fake-session").apply();
Probe failure=new Probe(c);failure.restore();failure.deadline=SystemClock.elapsedRealtime()+90000;
p.edit().putLong("nextReportAt",0).putLong("lastLiveAt",0).apply();DisplayApi.offline=true;failure.cycle();
check(p.getBoolean("reportPending",false),"HTTP failure preserves overdue report for retry");DisplayApi.offline=false;failure.dispose();
p.edit().putBoolean("reportPending",false).putLong("nextReportAt",now+7200000).apply();
Probe receipt=new Probe(c);receipt.restore();receipt.deadline=SystemClock.elapsedRealtime()+90000;receipt.cycle();
check(p.getLong("nextReportAt",0)==now+7200000,"receipt retry never advances configured upload cadence");receipt.dispose();
Probe service=new Probe(c);service.onStartCommand(new Intent("SAMPLE").putExtra("session","test"),0,1);
check(service.listens==1&&service.capturing,"scheduled wake starts one sample");
Location fix=new Location("fixture");fix.setLatitude(0);fix.setLongitude(0);fix.setAccuracy(12);fix.setTime(System.currentTimeMillis());fix.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
service.onLocationChanged(fix);check(!service.capturing,"first fix releases listener immediately");
new Handler().postDelayed(()->{
check(service.finishes>0,"scheduled cycle completes");check(p.getBoolean("active",false),"logical sharing survives sample completion");
check(p.getLong("nextSampleAt",0)>System.currentTimeMillis(),"next sample scheduled");
check(p.getLong("nextReportAt",0)==now+7200000,"sampling does not advance upload cadence");
check(service.queue.remembered!=null&&service.queue.appended==1,"fix and history persisted once");
service.dispose();
Probe sync=new Probe(c);sync.onStartCommand(new Intent("SYNC"),0,2);
new Handler().postDelayed(()->{
check(sync.listens==0,"manual sync never starts GPS");check(sync.finishes>0,"sync cycle completes");
sync.dispose();
Probe offline=new Probe(c);offline.online=false;offline.onStartCommand(new Intent("SYNC"),0,3);
new Handler().postDelayed(()->{
check(offline.finishes>0&&!offline.capturing,"offline sync sleeps instead of permanent service");check(p.getBoolean("reportPending",false),"offline work is retained");offline.dispose();
Probe stop=new Probe(c);stop.online=false;stop.onStartCommand(new Intent("STOP"),0,4);
new Handler().postDelayed(()->{
check(!p.getBoolean("active",true)&&p.getBoolean("stopPending",false),"offline stop prevents new sampling immediately");
check(stop.finishes>0&&!stop.capturing,"offline stop service terminates");stop.dispose();
p.edit().putBoolean("active",true).putBoolean("stopPending",false).putString("sessionNonce","new").apply();
Probe realtime=new Probe(c);realtime.active=true;realtime.realtime=true;realtime.capturing=true;realtime.captureStarted=System.currentTimeMillis();realtime.collectionStarted=now-10000;
fix.setTime(System.currentTimeMillis());fix.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());realtime.onLocationChanged(fix);
check(realtime.capturing,"explicit realtime retains listener");
new Handler().postDelayed(()->{realtime.dispose();p.edit().putBoolean("active",false).putBoolean("reportPending",false).apply();done.run();},150);
},200);
},200);
},200);
},250);
}
}
@@ -18,7 +18,7 @@ public class PhonePreviewActivity extends LocationActivity {
// Limit the actual Activity layout to a phone viewport without changing display configuration.
((android.view.ViewGroup)phone.getParent()).removeView(phone);FrameLayout outer=new FrameLayout(this);outer.setBackgroundColor(PhoneStyle.PAPER);
int width="narrow".equals(mode)||"large".equals(mode)?320:390;outer.addView(phone,new FrameLayout.LayoutParams(style.dp(width),style.dp("narrow".equals(mode)?640:844),Gravity.TOP|Gravity.CENTER_HORIZONTAL));previewRoot=phone;setContentView(outer);
new Handler().postDelayed(()->{try{exercise();if(mode.equals("history"))exerciseHistory();else save();}catch(Exception e){throw new RuntimeException(e);}},1800);
new Handler().postDelayed(()->{try{exercise();if(mode.equals("history"))exerciseHistory();else if(mode.equals("cycles"))LocationCycleChecks.run(this,this::save);else if(mode.equals("storage")){QueueStorageChecks.run(this);save();}else save();}catch(Exception e){throw new RuntimeException(e);}},1800);
}
void check(boolean condition,String message){if(!condition)throw new AssertionError(message);}
void exercise()throws Exception{
@@ -34,6 +34,11 @@ public class PhonePreviewActivity extends LocationActivity {
phone.nav.getChildAt(0).performClick();check(phone.tab==0,"family navigation");
check(!prefs.getBoolean("active",false),"navigation never enables sharing");
}
if(mode.equals("modes")){
selectTab(2);sharingMode.setSelection(1);check(samplePeriodSeconds()==10&&uploadPeriod()==10,"realtime fixes both cadences to ten seconds");
sharingMode.setSelection(0);check(samplePeriodSeconds()==300&&uploadPeriod()==7200,"scheduled controls retain independent cadences");
check(!prefs.getBoolean("active",false),"choosing a mode never enables sharing");
}
if(mode.equals("mine")||mode.equals("large"))selectTab(2);
else if(mode.equals("voice")||mode.equals("recording")||mode.equals("cancel")||mode.equals("narrow")||mode.equals("history")){
selectTab(1);voice.ui.removeCallbacks(voice.visual);VoiceSurface v=voice.page();v.expand.setVisibility(View.GONE);v.destination(new JSONObject("{\"name\":\"家庭显示终端\",\"kind\":\"display\",\"online\":true}"),true);v.recipient.setText("家庭显示终端");v.status.setText("界面验收 · 不录音、不发送语音");
@@ -0,0 +1,28 @@
package cn.ucvl.zhaodisplay;
import android.content.*;import android.database.sqlite.*;import org.json.*;
/** Production SQLite/Keystore logic runs under the fixture's separate UID and database. */
final class QueueStorageChecks {
static void check(boolean v,String msg){if(!v)throw new AssertionError(msg);}
static void run(Context c)throws Exception{
c.deleteDatabase("storage-check.db");SQLiteDatabase old=c.openOrCreateDatabase("storage-check.db",0,null);
old.execSQL("CREATE TABLE points(id TEXT PRIMARY KEY,owner TEXT NOT NULL,session TEXT NOT NULL,at INTEGER,payload BLOB NOT NULL,batch TEXT)");
old.execSQL("CREATE TABLE batches(id TEXT PRIMARY KEY,owner TEXT,session TEXT,payload BLOB,digest TEXT,count INTEGER,next_try INTEGER)");
old.execSQL("CREATE TABLE totals(owner TEXT PRIMARY KEY,uploaded INTEGER NOT NULL,freed INTEGER NOT NULL)");
old.execSQL("INSERT INTO points VALUES ('old','legacy','old-session',1,X'01',NULL)");old.setVersion(1);old.close();
StoredLocationQueue q=new StoredLocationQueue(c);
check(q.stats("legacy")[0]==1,"v1 pending rows survive migration");
check(q.getReadableDatabase().getVersion()==2,"database migrated to v2");
q.discard("legacy");String owner=StoredLocationQueue.digest("synthetic"),session="test-session";
JSONObject point=new JSONObject().put("latitude",0).put("longitude",0).put("accuracy",5).put("at",System.currentTimeMillis()/1000d);
q.latest(owner,point);check(q.latest(owner).getDouble("latitude")==0,"encrypted latest round trip");
check(q.append(owner,session,point),"encrypted sample persisted");
StoredLocationQueue.Batch batch=q.next(owner,System.currentTimeMillis()+1000,System.currentTimeMillis());
check(batch!=null,"batch created");JSONObject accepted=new JSONObject().put("batchId",batch.id).put("sha256",batch.digest).put("count",batch.count).put("state","accepted");
check(!q.acknowledge(owner,batch,accepted)&&q.stats(owner)[0]==1,"accepted receipt keeps local data");
try{q.acknowledge(owner,batch,new JSONObject(accepted.toString()).put("sha256","wrong").put("state","verified"));throw new AssertionError("mismatched receipt accepted");}catch(SecurityException expected){}
check(q.stats(owner)[0]==1,"invalid receipt keeps pending row");
check(q.acknowledge(owner,batch,accepted.put("state","verified")),"verified receipt clears batch");
check(q.stats(owner)[0]==0&&q.stats(owner)[2]==1,"only verified point removed");
q.clearLatest(owner);check(q.latest(owner)==null,"latest removed on stop");q.close();c.deleteDatabase("storage-check.db");
}
}