feat(location): durable offline GPS outbox and hourly daily uploads v0.1.50

This commit is contained in:
Codex
2026-10-19 00:57:33 +08:00
parent cd3ed420a2
commit e3afb2e07f
26 changed files with 697 additions and 135 deletions
+2 -2
View File
@@ -1,4 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="5" android:versionName="0.1.49">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="6" android:versionName="0.1.50">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
@@ -17,6 +17,6 @@
</activity>
<service android:name=".MonitorService" android:exported="false" />
<activity android:name=".LocationActivity" android:label="赵府家人位置" android:exported="true" />
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location" />
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location|dataSync" />
</application>
</manifest>
+2 -2
View File
@@ -1,4 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="5" android:versionName="0.1.49">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="6" android:versionName="0.1.50">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
@@ -15,7 +15,7 @@
</activity>
<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"/>
<service android:name=".LocationService" android:exported="false" android:foregroundServiceType="location|dataSync"/>
<receiver android:name=".BootReceiver" android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
</application>
</manifest>
@@ -15,7 +15,9 @@ 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;LinearLayout settings,recipients,familyList,homeContent,shareControls;
CheckBox consent,historyConsent;Switch sharing;Spinner cadence,sampleCadence,customUnit;EditText customAmount;LinearLayout customPeriod,settings,recipients,familyList,homeContent,shareControls;
TextView queueStatus;LocationQueue outbox;String queueOwner="";
final int[] uploadIntervals={10,60,300,3600,7200,10800,14400,18000,86400,172800,259200,0};
TextView historyStatus,historyNotice;Dialog historyDialog;LocationMapView historyMap;Button historyMore;JSONArray historyPoints=new JSONArray();int historyRequest=0;boolean historyAcknowledged=false;
VoicePanel voice;Button settingsButton;
LocationMapView map;boolean rendering=false,visible=false,loading=false,settingsReady=false,pendingStart=false;
@@ -28,6 +30,7 @@ public class LocationActivity extends Activity {
Button button(String label,LinearLayout parent){Button b=new Button(this);b.setText(label);parent.addView(b);return b;}
public void onCreate(Bundle state){
super.onCreate(state);prefs=getSharedPreferences("location",0);
outbox=new LocationQueue(this);refreshQueueStats();
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.
@@ -49,13 +52,20 @@ public class LocationActivity extends Activity {
shareControls=new LinearLayout(this);shareControls.setOrientation(1);settings.addView(shareControls);
text("我的位置共享",22,shareControls);text("选择谁能看我的位置",16,shareControls);
recipients=new LinearLayout(this);recipients.setOrientation(1);shareControls.addView(recipients);
text("上传频率",16,shareControls);cadence=new Spinner(this);cadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"实时(约 10 秒)","每 1 分钟","每 5 分钟(默认)"}));cadence.setSelection(2);shareControls.addView(cadence);
text("实时档更耗电和流量;更新受信号、网络与系统省电影响。调整名单或频率前,先关闭共享。",14,shareControls);
text("定位采集频率",16,shareControls);sampleCadence=new Spinner(this);sampleCadence.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,new String[]{"每 10 秒(较耗电)","每 1 分钟(默认)","每 5 分钟(省电)"}));sampleCadence.setSelection(1);shareControls.addView(sampleCadence);
text("集中上传周期",16,shareControls);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);shareControls.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);shareControls.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,shareControls);
historyConsent=new CheckBox(this);historyConsent.setText("另行同意保存我的历史轨迹到家庭网盘,长期保留至我手动删除;共享期间允许所选查看人读取其获授权期间的记录。");shareControls.addView(historyConsent);
historyStatus=text("未开启时不保存历史轨迹。关闭共享只清除当前位置,已保存历史可在下方删除。",14,shareControls);
button("查看我的历史轨迹",shareControls).setOnClickListener(v->history(""));
button("删除我的全部历史轨迹",shareControls).setOnClickListener(v->new AlertDialog.Builder(this).setTitle("删除自己的历史轨迹").setMessage("历史将立即隐藏,网盘文件随后删除;此操作不能撤销。若仍开启共享和历史保存,之后的新位置会继续记录。").setNegativeButton("取消",null).setPositiveButton("确认删除",(d,w)->deleteHistory()).show());
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述频率共享实时位置。关闭后停止采集并清除当前位置。");shareControls.addView(consent);
queueStatus=text("",15,shareControls);
button("立即同步待上传轨迹",shareControls).setOnClickListener(v->syncNow());
text("本机待同步上限:50,000 个点或 12 MiB 密文,先到为准。达到上限暂停新增历史,保留未上传记录。只有网盘完整回读校验通过才自动清理对应批次;手机数据库文件最多 32 MiB,空页循环复用。",13,shareControls);
button("放弃本机待同步记录",shareControls).setOnClickListener(v->new AlertDialog.Builder(this).setTitle("放弃尚未同步完的轨迹").setMessage("将停止本机共享并删除本机待同步副本,未上传内容无法恢复。已经被平台接收的记录不受此操作影响;如需彻底删除,请使用“删除我的全部历史轨迹”。").setNegativeButton("保留记录",null).setPositiveButton("确认放弃",(d,w)->discardLocal()).show());
button("删除我的全部历史轨迹",shareControls).setOnClickListener(v->new AlertDialog.Builder(this).setTitle("删除自己的历史轨迹").setMessage("将暂停共享、清空本机待同步轨迹并隐藏平台历史,网盘文件随后删除;此操作不能撤销。以后可重新开启共享和记录。").setNegativeButton("取消",null).setPositiveButton("确认删除",(d,w)->deleteHistory()).show());
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述周期采集和共享位置。启用历史保存后,断网会加密暂存并补传。关闭后停止新采集并清除当前位置,关闭前已采集轨迹仍会完成上传。");shareControls.addView(consent);
sharing=new Switch(this);sharing.setText("共享我的位置");sharing.setTextSize(20);sharing.setPadding(0,20,0,20);shareControls.addView(sharing);
sharing.setOnCheckedChangeListener((v,checked)->{if(rendering)return;if(checked)start();else{startService(new Intent(this,LocationService.class).setAction("STOP"));consent.setChecked(false);}render();});
permissionStatus=text("",14,shareControls);
@@ -80,23 +90,26 @@ public class LocationActivity extends Activity {
long expires=prefs.getLong("expires",0);
identity.setText(prefs.getString("memberName","尚未配对本人")+" · "+prefs.getString("home","请在我的位置设置中配对")+(expires>0?"\n配对有效至 "+java.text.DateFormat.getDateTimeInstance().format(new Date(expires)):""));
status.setText(settingsError.isEmpty()?"我的位置:"+prefs.getString("status","共享关闭,不采集定位"):settingsError);
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||!busy&&settingsReady));
pair.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);historyConsent.setEnabled(!active&&!busy&&settingsReady);
sampleCadence.setEnabled(!active&&!busy);customAmount.setEnabled(!active&&!busy);customUnit.setEnabled(!active&&!busy);
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)).apply();
prefs.edit().putString("receipt",response.getString("receipt")).putString("recipients",names.toString()).putInt("intervalSeconds",response.optInt("intervalSeconds",300)).putInt("sampleIntervalSeconds",response.optInt("sampleIntervalSeconds",60)).apply();
}
void pair(){
if(pairing||LocationService.busy||prefs.getBoolean("active",false))return;
if(outbox.total()>0){Toast.makeText(this,"还有本机待同步轨迹,请先完成同步,或明确放弃后再更换配对",1).show();return;}
String value=code.getText().toString().trim();if(!value.matches("[0-9]{8}")){Toast.makeText(this,"请输入八位手机配对码",1).show();return;}
pairing=true;render();
new Thread(()->{try{
JSONObject response=DisplayApi.call("/api/location/pair",null,new JSONObject().put("code",value).put("consentProtocol",3));remember(response);
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();
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;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;settings.setVisibility(View.GONE);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();
}
@@ -106,9 +119,9 @@ public class LocationActivity extends Activity {
new Thread(()->{try{
JSONObject response=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","list"));
runOnUiThread(()->{if(!visible||g!=generation)return;JSONArray list=response.optJSONArray("items");map.setItems(list);familyList.removeAllViews();viewStatus.setText(list==null||list.length()==0?"尚无家人授权给这台手机的位置。请对方在自己的位置设置里勾选你的手机,并开启共享。":"只显示仍在授权有效期内的最新位置。");
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("stale".equals(row.optString("status"))?"更新中断,旧坐标已隐藏":"等待定位") : String.format(Locale.CHINA,"纬度 %.5f · 经度 %.5f\n精度约 %.0f 米 · %s",pos.optDouble("latitude"),pos.optDouble("longitude"),pos.optDouble("accuracy"),java.text.DateFormat.getTimeInstance().format(new Date((long)(pos.optDouble("at")*1000))));Button item=button(row.optString("name")+"\n"+detail,familyList);item.setAllCaps(false);item.setOnClickListener(v->{if(pos!=null)map.focus(pos);});button("查看 "+row.optString("name")+" 的已授权历史",familyList).setOnClickListener(v->history(row.optString("id")));}
if(list!=null)for(int i=0;i<list.length();i++){JSONObject row=list.optJSONObject(i);if(row==null)continue;JSONObject pos=row.optJSONObject("position");String detail=pos==null?("scheduled".equals(row.optString("status"))?"按设定周期上传中,当前没有实时坐标":("stale".equals(row.optString("status"))?"更新中断,旧坐标已隐藏":"等待定位")) : String.format(Locale.CHINA,"纬度 %.5f · 经度 %.5f\n精度约 %.0f 米 · %s",pos.optDouble("latitude"),pos.optDouble("longitude"),pos.optDouble("accuracy"),java.text.DateFormat.getTimeInstance().format(new Date((long)(pos.optDouble("at")*1000))));Button item=button(row.optString("name")+"\n"+detail,familyList);item.setAllCaps(false);item.setOnClickListener(v->{if(pos!=null)map.focus(pos);});button("查看 "+row.optString("name")+" 的已授权历史",familyList).setOnClickListener(v->history(row.optString("id")));}
});
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403)){prefs.edit().remove("token").putBoolean("active",false).apply();startService(new Intent(this,LocationService.class).setAction("STOP"));voice.rebound();settings.setVisibility(View.VISIBLE);}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());if(e instanceof DisplayApi.ApiError&&(((DisplayApi.ApiError)e).status==401||((DisplayApi.ApiError)e).status==403)){boolean wasSharing=prefs.getBoolean("active",false);prefs.edit().putBoolean("active",false).apply();if(wasSharing||LocationService.busy)startService(new Intent(this,LocationService.class).setAction("STOP"));voice.rebound();settings.setVisibility(View.VISIBLE);}viewStatus.setText(e instanceof DisplayApi.ApiError&&((DisplayApi.ApiError)e).status==401?"手机配对已过期或解除,请重新配对。":"位置未能刷新,已隐藏旧画面,请检查网络。");});}finally{runOnUiThread(()->{if(g==generation){loading=false;render();}});}},"family-positions").start();
}
void loadSettings(){
String token=prefs.getString("token","");if(token.isEmpty()||pairing)return;int g=generation,request=++settingsRequest;settingsReady=false;settingsError="";render();
@@ -116,7 +129,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);cadence.setSelection(seconds==10?0:seconds==60?1:2);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();});
int seconds=result.optInt("intervalSeconds",300);setUploadPeriod(seconds);int sample=result.optInt("sampleIntervalSeconds",60);sampleCadence.setSelection(sample==10?0:sample==300?2:1);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;settingsError="无法读取我的位置设置,请检查网络或配对有效期,重新打开设置重试。";render();}});}},"location-settings").start();
}
void start(){
@@ -125,12 +138,17 @@ public class LocationActivity extends Activity {
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(!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;}body.put("action","configure").put("consent",true).put("receipt",settingsReceipt).put("intervalSeconds",new int[]{10,60,300}[cadence.getSelectedItemPosition()]).put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){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",new int[]{10,60,300}[sampleCadence.getSelectedItemPosition()]).put("historyEnabled",historyConsent.isChecked()).put("historyConsent",historyConsent.isChecked());}catch(Exception e){Toast.makeText(this,"请填写 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 uploadPeriod(){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 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();
@@ -156,7 +174,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;new Thread(()->{try{DisplayApi.call("/api/location/update",prefs.getString("token",""),new JSONObject().put("action","history-delete").put("confirm",true));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();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 "定位权限:未允许。查看家人不需要开启自己的定位。";
@@ -176,7 +194,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;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.getLong("pendingPoints",0)>0)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(map!=null)map.close();if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();}
}
@@ -2,7 +2,11 @@ package cn.ucvl.zhaodisplay;
/** Shared scheduling rule, independent of Android for deterministic testing. */
final class LocationCadence {
static int seconds(int value){return value==10||value==60||value==300?value:300;}
static final int MAX_SECONDS=30*86400;
static boolean valid(int value){return value==10||value==60||value==300||value>=3600&&value<=MAX_SECONDS&&value%3600==0;}
static int seconds(int value){return valid(value)?value:300;}
static int sample(int value){return value==10||value==60||value==300?value:60;}
static int custom(int value,boolean days){long seconds=value*(days?86400L:3600L);if(value<1||seconds>MAX_SECONDS)throw new IllegalArgumentException("周期需在 1 小时至 30 天内");return (int)seconds;}
static boolean due(long now,long lastAttempt,int interval,boolean firstFix){
return lastAttempt==0||now-lastAttempt>=1000L*(firstFix?10:seconds(interval));
}
@@ -0,0 +1,95 @@
package cn.ucvl.zhaodisplay;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.*;
import android.security.keystore.*;
import org.json.*;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.*;
/** Private, encrypted outbox. Only a matching cloud-verification receipt releases rows. */
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);}
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)");
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){throw new IllegalStateException("Unsupported location outbox migration");}
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{
byte[] bytes=MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));StringBuilder result=new StringBuilder();for(byte b:bytes)result.append(String.format(Locale.US,"%02x",b&255));return result.toString();
}
private SecretKey key()throws Exception{
synchronized(LocationQueue.class){KeyStore store=KeyStore.getInstance("AndroidKeyStore");store.load(null);if(!store.containsAlias(KEY)){
KeyGenerator generator=KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,"AndroidKeyStore");
generator.init(new KeyGenParameterSpec.Builder(KEY,KeyProperties.PURPOSE_ENCRYPT|KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).setKeySize(256).build());generator.generateKey();
}return (SecretKey)store.getKey(KEY,null);}
}
private byte[] encrypt(String value,String aad)throws Exception{
Cipher cipher=Cipher.getInstance("AES/GCM/NoPadding");cipher.init(Cipher.ENCRYPT_MODE,key());cipher.updateAAD(aad.getBytes(StandardCharsets.UTF_8));byte[] encrypted=cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)),iv=cipher.getIV();byte[] out=new byte[iv.length+encrypted.length];System.arraycopy(iv,0,out,0,iv.length);System.arraycopy(encrypted,0,out,iv.length,encrypted.length);return out;
}
private String decrypt(byte[] value,String aad)throws Exception{
Cipher cipher=Cipher.getInstance("AES/GCM/NoPadding");cipher.init(Cipher.DECRYPT_MODE,key(),new GCMParameterSpec(128,Arrays.copyOfRange(value,0,12)));cipher.updateAAD(aad.getBytes(StandardCharsets.UTF_8));return new String(cipher.doFinal(value,12,value.length-12),StandardCharsets.UTF_8);
}
synchronized boolean append(String owner,String session,JSONObject position)throws Exception{
SQLiteDatabase db=getWritableDatabase();String id=id();byte[] encrypted=encrypt(new JSONObject().put("id",id).put("position",position).toString(),owner+id);
db.beginTransaction();try{
try(Cursor cursor=db.rawQuery("SELECT count(*),coalesce(sum(length(payload)),0) FROM points",null)){cursor.moveToFirst();if(cursor.getLong(0)>=MAX_POINTS||cursor.getLong(1)+encrypted.length>MAX_BYTES)return false;}
ContentValues row=new ContentValues();row.put("id",id);row.put("owner",owner);row.put("session",session);row.put("at",(long)(position.getDouble("at")*1000));row.put("payload",encrypted);db.insertOrThrow("points",null,row);db.setTransactionSuccessful();return true;
}catch(SQLiteFullException full){return false;}finally{db.endTransaction();}
}
static final class Batch {
final String id,payload,digest;final int count;
Batch(String id,String payload,String digest,int count){this.id=id;this.payload=payload;this.digest=digest;this.count=count;}
JSONObject request()throws Exception{return new JSONObject().put("action","history-batch").put("batchId",id).put("sha256",digest).put("payload",payload);}
}
synchronized Batch next(String owner,long cutoff,long now)throws Exception{
SQLiteDatabase db=getWritableDatabase();db.beginTransaction();try{
try(Cursor c=db.rawQuery("SELECT id,payload,digest,count FROM batches WHERE owner=? AND next_try<=? ORDER BY next_try,id LIMIT 1",new String[]{owner,Long.toString(now)})){
if(c.moveToFirst())return new Batch(c.getString(0),decrypt(c.getBlob(1),owner+c.getString(0)),c.getString(2),c.getInt(3));
}
if(cutoff<=0)return null;
try(Cursor c=db.rawQuery("SELECT count(*) FROM batches WHERE owner=?",new String[]{owner})){c.moveToFirst();if(c.getInt(0)>=MAX_INFLIGHT)return null;}
String session=null;
try(Cursor c=db.rawQuery("SELECT session FROM points WHERE owner=? AND batch IS NULL AND at<=? ORDER BY at,id LIMIT 1",new String[]{owner,Long.toString(cutoff)})){if(c.moveToFirst())session=c.getString(0);}
if(session==null)return null;
JSONArray points=new JSONArray();List<String> ids=new ArrayList<>();
try(Cursor c=db.rawQuery("SELECT id,payload FROM points WHERE owner=? AND session=? AND batch IS NULL AND at<=? ORDER BY at,id LIMIT "+BATCH_POINTS,new String[]{owner,session,Long.toString(cutoff)})){
while(c.moveToNext()){ids.add(c.getString(0));points.put(new JSONObject(decrypt(c.getBlob(1),owner+c.getString(0))));}
}
String id=id(),payload=new JSONObject().put("version",1).put("collectionId",session).put("points",points).toString(),sha=digest(payload);
ContentValues row=new ContentValues();row.put("id",id);row.put("owner",owner);row.put("session",session);row.put("payload",encrypt(payload,owner+id));row.put("digest",sha);row.put("count",points.length());row.put("next_try",0);db.insertOrThrow("batches",null,row);
for(String point:ids)db.execSQL("UPDATE points SET batch=? WHERE id=? AND owner=?",new Object[]{id,point,owner});
db.setTransactionSuccessful();return new Batch(id,payload,sha,points.length());
}finally{db.endTransaction();}
}
synchronized boolean acknowledge(String owner,Batch batch,JSONObject receipt)throws Exception{
if(!batch.id.equals(receipt.optString("batchId"))||!batch.digest.equals(receipt.optString("sha256"))||batch.count!=receipt.optInt("count",-1))throw new SecurityException("上传回执不匹配,本地记录已保留");
String state=receipt.optString("state");if(!"accepted".equals(state)&&!"verified".equals(state))throw new SecurityException("未收到完整校验回执,本地记录已保留");
SQLiteDatabase db=getWritableDatabase();db.beginTransaction();try{
if("accepted".equals(state)){db.execSQL("UPDATE batches SET next_try=? WHERE id=? AND owner=?",new Object[]{System.currentTimeMillis()+30000,batch.id,owner});db.setTransactionSuccessful();return false;}
long count,bytes;try(Cursor c=db.rawQuery("SELECT count(*),coalesce(sum(length(payload)),0) FROM points WHERE owner=? AND batch=?",new String[]{owner,batch.id})){c.moveToFirst();count=c.getLong(0);bytes=c.getLong(1);}
if(count!=batch.count)throw new SecurityException("本地批次条数不匹配,未清理");
db.delete("points","owner=? AND batch=?",new String[]{owner,batch.id});db.delete("batches","owner=? AND id=?",new String[]{owner,batch.id});
db.execSQL("INSERT OR IGNORE INTO totals VALUES (?,0,0)",new Object[]{owner});db.execSQL("UPDATE totals SET uploaded=uploaded+?,freed=freed+? WHERE owner=?",new Object[]{count,bytes,owner});db.setTransactionSuccessful();return true;
}finally{db.endTransaction();}
}
synchronized long[] stats(String owner){
SQLiteDatabase db=getReadableDatabase();long[] values=new long[4];
try(Cursor c=db.rawQuery("SELECT count(*),coalesce(sum(length(payload)),0) FROM points WHERE owner=?",new String[]{owner})){c.moveToFirst();values[0]=c.getLong(0);values[1]=c.getLong(1);}
try(Cursor c=db.rawQuery("SELECT uploaded,freed FROM totals WHERE owner=?",new String[]{owner})){if(c.moveToFirst()){values[2]=c.getLong(0);values[3]=c.getLong(1);}}
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();}}
}
@@ -4,97 +4,140 @@ import android.app.*;
import android.content.*;
import android.os.*;
import android.location.*;
import android.net.*;
import android.content.pm.PackageManager;
import android.Manifest;
import org.json.JSONObject;
import java.util.concurrent.*;
/** Visible, bounded sharing session. No boot receiver starts location collection. */
/** Visible sharing plus an encrypted outbox. No boot receiver starts GPS collection. */
public class LocationService extends Service implements LocationListener {
static volatile boolean busy=false;
String sessionToken="";
volatile boolean destroyed=false;
ScheduledExecutorService worker;LocationManager manager;android.content.SharedPreferences prefs;
volatile Location latest;volatile boolean active=false,stopping=false,starting=false;
long lastAttempt=0;boolean sentFix=false;int intervalSeconds=300;String lastSignal="";
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="";
final Handler ui=new Handler();
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 onCreate(){
super.onCreate();prefs=getSharedPreferences("location",0);manager=(LocationManager)getSystemService(LOCATION_SERVICE);
sessionToken=prefs.getString("token","");
NotificationManager nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel("location","本人位置共享",NotificationManager.IMPORTANCE_LOW));
worker=Executors.newSingleThreadScheduledExecutor();
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;}
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();
try{connectivity.registerDefaultNetworkCallback(networkCallback);}catch(Exception ignored){}
}
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 notice=new Notification.Builder(this,"location").setContentTitle("赵府 · 位置共享").setContentText(text).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentIntent(open).setOngoing(true).addAction(new Notification.Action.Builder(null,"停止共享",stop).build()).build();
if(android.os.Build.VERSION.SDK_INT>=29)startForeground(45,notice,stopping?0:android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);else startForeground(45,notice);
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());
}
public int onStartCommand(Intent intent,int flags,int id){
if(intent!=null&&"STOP".equals(intent.getAction())){stopSharing();return START_NOT_STICKY;}
if(intent==null){stopSelf();return START_NOT_STICKY;}
if(intent==null||sessionToken.isEmpty()){stopSelf();return START_NOT_STICKY;}
if(!ticking){ticking=true;worker.scheduleWithFixedDelay(this::tick,1,10,TimeUnit.SECONDS);}
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(active||stopping||starting)return START_NOT_STICKY;
starting=true;busy=true;
final String receipt=prefs.getString("receipt","");
notification("正在确认本人的共享授权");
starting=true;busy=true;notification("正在确认本人的共享授权");
worker.execute(()->{try{
JSONObject r=DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","start").put("consent",true).put("receipt",receipt));
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;
intervalSeconds=LocationCadence.seconds(r.optInt("intervalSeconds",300));
active=true;prefs.edit().putBoolean("active",true).putLong("expires",(long)(r.getDouble("expires")*1000)).putString("status","共享中,等待定位").apply();
ui.post(()->{if(!stopping){listen();notification("共享给 "+prefs.getString("recipients","")+" · 可随时停止");}});
worker.scheduleWithFixedDelay(this::upload,1,10,TimeUnit.SECONDS);
}catch(Exception e){if(!destroyed){prefs.edit().putBoolean("active",false).putString("status","未开启:请检查网络、配对有效期").apply();stopSelf();}}});
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();
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();}}});
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,intervalSeconds*1000L,0,this);}
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 upload(){
if(!active||stopping)return;
if(System.currentTimeMillis()>prefs.getLong("expires",0)){ui.post(this::stopSharing);return;}
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(){
if(destroyed||starting)return;
try{
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";
// Permission/setting loss must clear the server fix without waiting five minutes.
boolean safetyChange=(!"waiting".equals(signal)&&!signal.equals(lastSignal));
if(!LocationCadence.due(SystemClock.elapsedRealtime(),lastAttempt,intervalSeconds,safetyChange||latest!=null&&!sentFix))return;
lastAttempt=SystemClock.elapsedRealtime();
JSONObject body=new JSONObject().put("action","update");Location fix=latest;
if(fix!=null&&"waiting".equals(signal)&&SystemClock.elapsedRealtimeNanos()-fix.getElapsedRealtimeNanos()<900000000000L){
body.put("position",new JSONObject().put("latitude",fix.getLatitude()).put("longitude",fix.getLongitude()).put("accuracy",fix.getAccuracy()).put("at",fix.getTime()/1000d));signal="available";
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;
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;
}
body.put("signal",signal);DisplayApi.call("/api/location/update",sessionToken,body);
lastSignal=signal;
if("available".equals(signal))sentFix=true;
if(stopping||destroyed)return;
String message="available".equals(signal)?"共享中 · 最近更新 "+java.text.DateFormat.getTimeInstance().format(new java.util.Date()):"共享中 · 等待定位,请检查手机定位和权限";
prefs.edit().putString("status",message).apply();
}catch(DisplayApi.ApiError e){if(e.status==401||e.status==403)ui.post(this::stopSharing);else prefs.edit().putString("status","网络未同步,稍后自动重试").apply();}
catch(Exception e){prefs.edit().putString("status","网络未同步,稍后自动重试").apply();}
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;
}
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;
boolean removed=queue.acknowledge(owner,batch,reply);
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("网络或同步暂未完成,手机轨迹已保留,恢复后自动补传");}
}
static boolean locationEnabled(LocationManager manager){
if(Build.VERSION.SDK_INT>=28)return manager.isLocationEnabled();
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER)||manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
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{
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;busy=true;active=false;latest=null;
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("本机已停止定位 · 正在通知平台清除");
worker.scheduleWithFixedDelay(()->{try{
String token=sessionToken;
if(!token.isEmpty())try{DisplayApi.call("/api/location/update",token,new JSONObject().put("action","stop"));}catch(DisplayApi.ApiError e){if(e.status!=401&&e.status!=403)throw e;}
if(destroyed)return;
prefs.edit().putBoolean("active",false).putString("status","共享关闭,平台已清除当前位置").apply();stopSelf();
}catch(Exception e){prefs.edit().putString("status","本机已停止,联网后清除平台位置,旧坐标最长 15 分钟后隐藏,也可在平台解除授权").apply();}},0,30,TimeUnit.SECONDS);
prefs.edit().putBoolean("active",false).putString("status","本机已停止采集,联网后通知平台清除当前位置;关闭前轨迹仍会补传").apply();notification("已停止定位 · 联网后完成同步");nextAttempt=0;
}
public void onLocationChanged(Location value){
if(!active||stopping)return;latest=new Location(value);if(!historyEnabled)return;
Location fix=new Location(value);String session=collection;long epoch=prefs.getLong("queueEpoch",0),started=collectionStarted;
recorder.execute(()->{try{
if(epoch!=prefs.getLong("queueEpoch",0))return;
long elapsed=fix.getElapsedRealtimeNanos()/1000000;
if(lastSample!=0&&elapsed-lastSample<sampleSeconds*1000L||fix.getTime()<started-5000||fix.getTime()>System.currentTimeMillis()+60000||System.currentTimeMillis()-fix.getTime()>900000)return;
if(queue.append(owner,session,position(fix))){lastSample=elapsed;cacheFull=false;}
else{cacheFull=true;prefs.edit().putString("syncStatus","本地缓存已达上限,暂停新增历史;未上传记录没有覆盖,请联网补传").apply();notification("轨迹缓存已满 · 请联网补传");}
updateQueueStatus();
}catch(Exception error){cacheFull=true;prefs.edit().putString("syncStatus","本地轨迹未能写入,请检查手机存储空间;已有记录保留").apply();}});
}
public void onLocationChanged(Location value){if(active&&!stopping)latest=new Location(value);}
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;}
public void onDestroy(){destroyed=true;active=false;latest=null;try{manager.removeUpdates(this);}catch(Exception ignored){}if(worker!=null)worker.shutdownNow();prefs.edit().putBoolean("active",false).apply();busy=false;super.onDestroy();}
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();
}
}
@@ -5,7 +5,7 @@ public class LocationCadenceTest {
static void require(boolean value){if(!value)throw new AssertionError();}
public static void main(String[] args){
int assertions=0;
for(int seconds:new int[]{10,60,300}){
for(int seconds:new int[]{10,60,300,3600,7200,10800,14400,18000,23*3600,86400,172800,259200,30*86400}){
require(LocationCadence.seconds(seconds)==seconds);assertions++;
require(LocationCadence.due(100000,0,seconds,false));assertions++;
require(!LocationCadence.due(1000+seconds*1000L-1,1000,seconds,false));assertions++;
@@ -13,7 +13,10 @@ public class LocationCadenceTest {
require(!LocationCadence.due(10999,1000,seconds,true));assertions++;
require(LocationCadence.due(11000,1000,seconds,true));assertions++;
}
for(int invalid:new int[]{-1,0,9,59,301}){require(LocationCadence.seconds(invalid)==300);assertions++;}
for(int invalid:new int[]{-1,0,9,59,301,3601,31*86400,Integer.MAX_VALUE}){require(LocationCadence.seconds(invalid)==300);assertions++;}
require(LocationCadence.custom(3,true)==259200);assertions++;
require(LocationCadence.custom(5,false)==18000);assertions++;
for(int invalid:new int[]{-1,0,721,Integer.MAX_VALUE}){try{LocationCadence.custom(invalid,false);throw new AssertionError();}catch(IllegalArgumentException expected){assertions++;}}
System.out.println("Location cadence: "+assertions+" assertions passed");
}
}
@@ -0,0 +1,43 @@
package cn.ucvl.zhaodisplay;
import android.app.*;
import android.os.Bundle;
import android.database.Cursor;
import org.json.*;
import java.nio.charset.StandardCharsets;
/** Isolated test package only. No GPS permission, family token or production data. */
public final class QueueInstrumentation extends Instrumentation {
int assertions=0;
void check(boolean condition){assertions++;if(!condition)throw new AssertionError("Assertion "+assertions);}
JSONObject position(double at)throws Exception{return new JSONObject().put("latitude",12.345678).put("longitude",45.678901).put("accuracy",7).put("at",at);}
JSONObject receipt(LocationQueue.Batch b,String state)throws Exception{return new JSONObject().put("batchId",b.id).put("sha256",b.digest).put("count",b.count).put("state",state);}
public void onCreate(Bundle args){super.onCreate(args);start();}
public void onStart(){Bundle result=new Bundle();LocationQueue queue=null;try{
getTargetContext().deleteDatabase("location-outbox.db");queue=new LocationQueue(getTargetContext());String owner=LocationQueue.digest("synthetic-owner"),other=LocationQueue.digest("synthetic-other"),session="a1111111111111111111111111111111";
for(int i=0;i<130;i++)check(queue.append(owner,session,position(1700000000+i)));
check(queue.append(other,session,position(1700000000)));
check(queue.stats(owner)[0]==130);check(queue.stats(other)[0]==1);
try(Cursor c=queue.getReadableDatabase().rawQuery("SELECT payload FROM points LIMIT 1",null)){c.moveToFirst();check(!new String(c.getBlob(0),StandardCharsets.UTF_8).contains("latitude"));}
LocationQueue.Batch batch=queue.next(owner,Long.MAX_VALUE,System.currentTimeMillis());check(batch.count==128);check(new JSONObject(batch.payload).getJSONArray("points").length()==128);
String digest=batch.digest,id=batch.id;queue.close();queue=new LocationQueue(getTargetContext());
batch=queue.next(owner,Long.MAX_VALUE,System.currentTimeMillis());check(batch.id.equals(id));check(batch.digest.equals(digest));check(queue.stats(owner)[0]==130);
try{queue.acknowledge(owner,batch,receipt(batch,"verified").put("sha256","f"));throw new AssertionError("Accepted corrupt receipt");}catch(SecurityException expected){assertions++;}
try{queue.acknowledge(owner,batch,receipt(batch,"verified").put("count",127));throw new AssertionError("Accepted partial receipt");}catch(SecurityException expected){assertions++;}
check(queue.stats(owner)[0]==130);check(!queue.acknowledge(owner,batch,receipt(batch,"accepted")));check(queue.stats(owner)[0]==130);
check(queue.append(owner,session,position(1700000500)));check(queue.acknowledge(owner,batch,receipt(batch,"verified")));check(queue.stats(owner)[0]==3);check(queue.stats(owner)[2]==128);check(queue.stats(other)[0]==1);
check(queue.next(owner,0,System.currentTimeMillis())==null);
batch=queue.next(owner,Long.MAX_VALUE,System.currentTimeMillis());check(batch.count==3);check(queue.acknowledge(owner,batch,receipt(batch,"verified")));check(queue.stats(owner)[0]==0);check(queue.stats(owner)[2]==131);check(queue.stats(owner)[3]>0);
queue.getWritableDatabase().beginTransaction();try{
for(int i=0;i<LocationQueue.MAX_POINTS-1;i++)queue.getWritableDatabase().execSQL("INSERT INTO points VALUES (?,?,?,0,?,NULL)",new Object[]{"cap-"+i,owner,session,new byte[16]});
queue.getWritableDatabase().setTransactionSuccessful();
}finally{queue.getWritableDatabase().endTransaction();}
check(queue.total()==LocationQueue.MAX_POINTS);check(!queue.append(owner,session,position(1700000600)));check(queue.total()==LocationQueue.MAX_POINTS);
queue.discard(owner);check(queue.stats(other)[0]==1);check(queue.stats(owner)[0]==0);
check(queue.append(owner,session,position(1700000700)));
queue.getWritableDatabase().execSQL("UPDATE points SET payload=zeroblob(40) WHERE owner=?",new Object[]{owner});
try{queue.next(owner,Long.MAX_VALUE,System.currentTimeMillis());throw new AssertionError("Decrypted corrupt payload");}catch(javax.crypto.AEADBadTagException expected){assertions++;}
check(queue.stats(owner)[0]==1);
result.putString("stream","PASS: "+assertions+" assertions; encrypted queue, restart, retry, receipts, owner isolation, capacity and tamper checks\n");finish(Activity.RESULT_OK,result);
}catch(Throwable error){result.putString("stream","FAIL: "+error.getClass().getSimpleName()+": "+error.getMessage()+"\n");finish(Activity.RESULT_CANCELED,result);}finally{if(queue!=null)queue.close();}}
}
@@ -0,0 +1,36 @@
param([string]$ToolRoot='C:\Users\Administrator\Documents\ChatGPT\优创未来\services\toplc-vpn-android\.tools')
$ErrorActionPreference='Stop'
$tests=Split-Path -Parent $MyInvocation.MyCommand.Path
$source=Split-Path -Parent $tests
$stage=Join-Path 'C:\CodexBuild' ('ZhaoQueueCheck-'+[guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $stage,"$stage\classes","$stage\dex" | Out-Null
$jdk=Join-Path $ToolRoot 'jdk-staging\jdk-21.0.12.1+1'
$sdk=Join-Path $ToolRoot 'android-sdk'
$bt=Join-Path $sdk 'build-tools\36.0.0'
$android=Join-Path $sdk 'platforms\android-37.0\android.jar'
$env:JAVA_HOME=$jdk
$env:Path="$jdk\bin;$env:Path"
@'
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay.queuecheck" android:versionCode="1" android:versionName="1">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
<application android:label="轨迹队列隔离测试" android:allowBackup="false"/>
<instrumentation android:name="cn.ucvl.zhaodisplay.QueueInstrumentation" android:targetPackage="cn.ucvl.zhaodisplay.queuecheck"/>
</manifest>
'@ | 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'}
& "$jdk\bin\javac.exe" -encoding UTF-8 -source 8 -target 8 -cp $android -d "$stage\classes" "$source\src\cn\ucvl\zhaodisplay\LocationQueue.java" "$tests\QueueInstrumentation.java"
if($LASTEXITCODE){throw 'Test Java compile failed'}
& "$jdk\bin\jar.exe" cf "$stage\classes.jar" -C "$stage\classes" .
& "$bt\d8.bat" --lib $android --min-api 26 --output "$stage\dex" "$stage\classes.jar"
if($LASTEXITCODE){throw 'Test Dex compile failed'}
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip=[IO.Compression.ZipFile]::Open("$stage\unsigned.apk",[IO.Compression.ZipArchiveMode]::Update)
try{[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$stage\dex\classes.dex",'classes.dex',[IO.Compression.CompressionLevel]::Optimal) | Out-Null}finally{$zip.Dispose()}
& "$bt\zipalign.exe" -f 4 "$stage\unsigned.apk" "$stage\aligned.apk"
$keystore=Join-Path $env:LOCALAPPDATA 'ZhaoDisplay\display-signing.jks'
& "$bt\apksigner.bat" sign --ks $keystore --ks-pass pass:android --key-pass pass:android --ks-key-alias zhaodisplay --out "$source\build\QueueCheck.apk" "$stage\aligned.apk"
if($LASTEXITCODE){throw 'Test APK signing failed'}
& "$bt\apksigner.bat" verify "$source\build\QueueCheck.apk"
if($LASTEXITCODE){throw 'Test APK verification failed'}
Write-Output "$source\build\QueueCheck.apk"