Release 0.1.49: self-hosted maps and consented cloud location history

This commit is contained in:
Codex
2026-10-19 00:00:12 +08:00
parent d0b3db7f82
commit a5d2399d2e
58 changed files with 2586 additions and 223 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="4" android:versionName="0.1.48">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="5" android:versionName="0.1.49">
<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="4" android:versionName="0.1.48">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.ucvl.zhaodisplay" android:versionCode="5" android:versionName="0.1.49">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="30"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
@@ -8,6 +8,7 @@
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<application android:label="赵府智家" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@android:style/Theme.Material.Light.NoActionBar">
<activity android:name=".MainActivity" android:label="赵府家庭显示终端" android:exported="true" android:configChanges="orientation|screenSize|keyboardHidden" android:launchMode="singleTask">
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LEANBACK_LAUNCHER"/></intent-filter>
@@ -14,8 +14,9 @@ import java.util.*;
/** Paired member identity, family viewing and voluntary sharing; no account or display UI. */
public class LocationActivity extends Activity {
static volatile boolean pairing=false;
TextView identity,status,viewStatus;EditText code;Button pair,reload;
CheckBox consent;Switch sharing;Spinner cadence;LinearLayout settings,recipients,familyList,homeContent,shareControls;
TextView identity,status,viewStatus,permissionStatus;EditText code;Button pair,reload;
CheckBox consent,historyConsent;Switch sharing;Spinner cadence;LinearLayout settings,recipients,familyList,homeContent,shareControls;
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;
int generation=0,settingsRequest=0;long lastList=0;String settingsReceipt="",settingsError="";
@@ -50,21 +51,29 @@ public class LocationActivity extends Activity {
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);
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述频率共享位置。关闭后停止采集并清除位置。");shareControls.addView(consent);
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);
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);
Button backgroundButton=button("后台定位权限 · 始终允许",shareControls);backgroundButton.setOnClickListener(v->backgroundPermission());
try{if(!java.util.Arrays.asList(getPackageManager().getPackageInfo(getPackageName(),PackageManager.GET_PERMISSIONS).requestedPermissions).contains(Manifest.permission.ACCESS_BACKGROUND_LOCATION))backgroundButton.setVisibility(View.GONE);}catch(Exception ignored){}
button("打开手机系统定位设置",shareControls).setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)));
settings.setVisibility(prefs.getString("token","").isEmpty()?View.VISIBLE:View.GONE);
homeContent=new LinearLayout(this);homeContent.setOrientation(1);layout.addView(homeContent);
text("家人现在的位置",22,homeContent);viewStatus=text("",16,homeContent);
map=new LocationMapView(this);homeContent.addView(map,new LinearLayout.LayoutParams(-1,(int)(260*getResources().getDisplayMetrics().density)));
text("世界位置概览 · 可拖动、双指缩放;点家人卡片定位。底图为本地陆地轮廓,不含道路。",13,homeContent);
map=new LocationMapView(this);homeContent.addView(map,new LinearLayout.LayoutParams(-1,(int)(360*getResources().getDisplayMetrics().density)));
text("智家内置地图 · 可拖动、双指缩放;点家人卡片查看道路位置。圆圈表示定位精度范围。",13,homeContent);
button("查看全部位置",homeContent).setOnClickListener(v->map.reset());
reload=button("刷新家人位置",homeContent);reload.setOnClickListener(v->loadFamily());
familyList=new LinearLayout(this);familyList.setOrientation(1);homeContent.addView(familyList);
voice=new VoicePanel(this,"phone",()->prefs.getString("token",""));root.addView(voice,new LinearLayout.LayoutParams(-1,-2));render();
}
void render(){
permissionStatus.setText(locationPermissionText());
boolean paired=!prefs.getString("token","").isEmpty(),active=prefs.getBoolean("active",false),busy=pairing||LocationService.busy;
homeContent.setVisibility(paired?View.VISIBLE:View.GONE);shareControls.setVisibility(paired?View.VISIBLE:View.GONE);settingsButton.setVisibility(paired?View.VISIBLE:View.GONE);voice.setVisibility(paired?View.VISIBLE:View.GONE);
if(!paired)settings.setVisibility(View.VISIBLE);
@@ -73,7 +82,7 @@ public class LocationActivity extends Activity {
status.setText(settingsError.isEmpty()?"我的位置:"+prefs.getString("status","共享关闭,不采集定位"):settingsError);
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);
pair.setEnabled(!active&&!busy);cadence.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);historyConsent.setEnabled(!active&&!busy&&settingsReady);
for(List<CheckBox> list:choices.values())for(CheckBox c:list)c.setEnabled(!active&&!busy);
reload.setEnabled(paired&&!loading&&!pairing);
}
@@ -97,7 +106,7 @@ 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);});}
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")));}
});
}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();
}
@@ -107,22 +116,67 @@ 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);settingsReady=true;render();});
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();});
}catch(Exception e){runOnUiThread(()->{if(visible&&g==generation&&request==settingsRequest){settingsReady=false;settingsError="无法读取我的位置设置,请检查网络或配对有效期,重新打开设置重试。";render();}});}},"location-settings").start();
}
void start(){
if(pairing||LocationService.busy||prefs.getBoolean("active",false)||!settingsReady)return;
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(!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()]);}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;}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 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();
}
public void onRequestPermissionsResult(int request,String[] permissions,int[] results){super.onRequestPermissionsResult(request,permissions,results);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;voice.active(true);lastList=0;if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}}
public void onPause(){visible=false;voice.active(false);generation++;loading=false;ui.removeCallbacksAndMessages(null);if(map!=null)map.setItems(new JSONArray());if(familyList!=null)familyList.removeAllViews();super.onPause();}
public void onDestroy(){if(voice!=null)voice.close();ui.removeCallbacksAndMessages(null);super.onDestroy();}
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();
if(choice==4){historyLoad(member,String.format(Locale.US,"%04d-%02d-%02d",c.get(Calendar.YEAR),c.get(Calendar.MONTH)+1,c.get(Calendar.DAY_OF_MONTH)),period,0,true);return;}
new DatePickerDialog(this,(view,y,m,d)->historyLoad(member,String.format(Locale.US,"%04d-%02d-%02d",y,m+1,d),period,0,true),c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH)).show();
}).show();
}
void historyLoad(String member,String date,String period,int cursor,boolean reset){
int g=generation,request=++historyRequest;String token=prefs.getString("token","");
if(historyMore!=null)historyMore.setEnabled(false);Toast.makeText(this,"正在从网盘读取历史…",0).show();
new Thread(()->{try{JSONObject result=DisplayApi.call("/api/location/update",token,new JSONObject().put("action","history-list").put("memberId",member).put("date",date).put("period",period).put("cursor",cursor));runOnUiThread(()->{
if(!visible||g!=generation||request!=historyRequest)return;
if(reset){
if(historyDialog!=null)historyDialog.dismiss();historyPoints=new JSONArray();LinearLayout box=new LinearLayout(this);box.setOrientation(1);historyNotice=text("",16,box);
historyMap=new LocationMapView(this);box.addView(historyMap,new LinearLayout.LayoutParams(-1,0,1));historyMore=button("继续加载",box);historyDialog=new Dialog(this);historyDialog.setContentView(box);
button("关闭",box).setOnClickListener(v->historyDialog.dismiss());historyDialog.setOnDismissListener(v->{historyRequest++;if(historyMap!=null){historyMap.close();historyMap=null;}historyPoints=new JSONArray();});
historyDialog.show();historyDialog.getWindow().setLayout(-1,-1);
}
if(historyMap==null)return;JSONArray added=result.optJSONArray("points");if(added!=null)for(int i=0;i<added.length();i++)historyPoints.put(added.optJSONObject(i));
if(historyPoints.length()>10000){JSONArray sampled=new JSONArray();for(int i=0;i<10000;i++)sampled.put(historyPoints.optJSONObject((int)Math.round(i*(historyPoints.length()-1)/9999.0)));historyPoints=sampled;}
historyMap.setTrack(historyPoints);historyNotice.setText(date+" · "+period+"\n已读取 "+result.optInt("loadedFiles")+" / "+result.optInt("totalFiles")+" 段 · "+historyPoints.length()+" 个采样点\n概览连线不代表道路路线。1 分钟后清除画面。");
int next=result.isNull("nextCursor")?-1:result.optInt("nextCursor",-1);historyMore.setVisibility(next<0?View.GONE:View.VISIBLE);historyMore.setEnabled(true);historyMore.setOnClickListener(v->historyLoad(member,date,period,next,false));
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();}
String locationPermissionText(){
boolean foreground=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==0||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==0;
if(!foreground)return "定位权限:未允许。查看家人不需要开启自己的定位。";
if(Build.VERSION.SDK_INT<29||checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)==0)return "定位权限:已允许后台定位。只有本人开启共享后才采集;可随时关闭。";
return "定位权限:仅使用期间允许。可选择始终允许;后台共享仍受系统省电设置影响。";
}
void backgroundPermission(){
if(Build.VERSION.SDK_INT<29){Toast.makeText(this,"当前系统无需单独申请后台定位权限",1).show();return;}
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=0&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=0){
new AlertDialog.Builder(this).setTitle("先允许定位").setMessage("请先允许使用期间定位,然后再设置始终允许。授权不会自动开启位置共享。").setNegativeButton("暂不设置",null).setPositiveButton("允许定位",(d,w)->requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},47)).show();return;
}
if(checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)==0){Toast.makeText(this,"已允许后台定位",0).show();return;}
String label=Build.VERSION.SDK_INT>=30?getPackageManager().getBackgroundPermissionOptionLabel().toString():"始终允许";
new AlertDialog.Builder(this).setTitle("后台位置共享").setMessage("本人开启共享后,允许在锁屏或切换应用时继续更新位置。请在位置权限中选择「"+label+"」。关闭共享立即停止采集;查看名单仍由你决定。你可以暂不设置,继续查看获授权家人。").setNegativeButton("暂不设置",null).setPositiveButton("去设置",(d,w)->{
if(Build.VERSION.SDK_INT==29)requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION},48);
else startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,android.net.Uri.parse("package:"+getPackageName())));
}).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 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();}
}
@@ -1,31 +1,42 @@
package cn.ucvl.zhaodisplay;
import android.content.Context;
import android.graphics.*;
import android.view.*;
import android.webkit.*;
import android.net.Uri;
import android.view.MotionEvent;
import org.json.*;
import java.io.*;
import java.util.*;
import java.io.ByteArrayInputStream;
/** Bundled Natural Earth outline; no coordinates sent to third-party map providers. */
final class LocationMapView extends View {
final Paint paint=new Paint(3);final List<JSONArray> rings=new ArrayList<>();
JSONArray items=new JSONArray();float zoom=1,lastX,lastY;double lon=0,lat=10;
final ScaleGestureDetector scale;
LocationMapView(Context context){super(context);setContentDescription("家人位置地图,可拖动和双指缩放");
try(InputStream input=context.getAssets().open("world-land.json")){ByteArrayOutputStream out=new ByteArrayOutputStream();byte[] buffer=new byte[4096];int n;while((n=input.read(buffer))>0)out.write(buffer,0,n);JSONArray polygons=new JSONObject(out.toString("UTF-8")).getJSONArray("features").getJSONObject(0).getJSONObject("geometry").getJSONArray("coordinates");for(int i=0;i<polygons.length();i++)rings.add(polygons.getJSONArray(i).getJSONArray(0));}catch(Exception ignored){}
scale=new ScaleGestureDetector(context,new ScaleGestureDetector.SimpleOnScaleGestureListener(){public boolean onScale(ScaleGestureDetector detector){zoom=Math.max(1,Math.min(64,zoom*detector.getScaleFactor()));invalidate();return true;}});
/** First-party map only. No pairing token or native bridge is exposed to JavaScript. */
final class LocationMapView extends WebView {
JSONArray items=new JSONArray(),track=new JSONArray();boolean ready=false,closed=false;
LocationMapView(Context context){
super(context);setContentDescription("家人位置地图,可拖动和双指缩放");
WebSettings s=getSettings();s.setJavaScriptEnabled(true);s.setDomStorageEnabled(false);
s.setAllowFileAccess(false);s.setAllowContentAccess(false);s.setGeolocationEnabled(false);
s.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);s.setMediaPlaybackRequiresUserGesture(true);
CookieManager.getInstance().setAcceptThirdPartyCookies(this,false);
setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request){return true;}
public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request){
Uri uri=request.getUrl();String path=uri.getPath();
if(!"https".equals(uri.getScheme())||!"zhao.ucvl.cn".equals(uri.getHost())||(uri.getPort()!=-1&&uri.getPort()!=443)||path==null||!(path.startsWith("/maps/")||path.startsWith("/ui/assets/")))return new WebResourceResponse("text/plain","UTF-8",new ByteArrayInputStream(new byte[0]));
return null;
}
public void onPageFinished(WebView view,String url){if(!closed&&url.startsWith("https://zhao.ucvl.cn/maps/phone")){ready=true;push();}}
public void onReceivedError(WebView view,WebResourceRequest request,WebResourceError error){if(request.isForMainFrame())ready=false;}
});
loadUrl("https://zhao.ucvl.cn/maps/phone");
}
void setItems(JSONArray value){items=value==null?new JSONArray():value;invalidate();}
void reset(){zoom=1;lon=0;lat=10;invalidate();}
void focus(JSONObject point){lon=point.optDouble("longitude");lat=point.optDouble("latitude");zoom=16;invalidate();}
float x(double value){return getWidth()/2f+(float)(value-lon)*getWidth()/360f*zoom;}
float y(double value){return getHeight()/2f-(float)(value-lat)*getWidth()/360f*zoom;}
protected void onDraw(Canvas canvas){super.onDraw(canvas);canvas.drawColor(0xffe6eeea);paint.setColor(0xffceddd4);paint.setStyle(Paint.Style.FILL);
for(JSONArray ring:rings){Path path=new Path();for(int i=0;i<ring.length();i++){JSONArray p=ring.optJSONArray(i);float px=x(p.optDouble(0)),py=y(p.optDouble(1));if(i==0)path.moveTo(px,py);else path.lineTo(px,py);}path.close();canvas.drawPath(path,paint);}
float density=getResources().getDisplayMetrics().density;paint.setTextSize(14*density);
for(int i=0;i<items.length();i++){JSONObject person=items.optJSONObject(i),point=person.optJSONObject("position");if(point==null)continue;float px=x(point.optDouble("longitude")),py=y(point.optDouble("latitude"));paint.setColor(0xff287764);canvas.drawCircle(px,py,5*density,paint);paint.setColor(0xff183e31);canvas.drawText(person.optString("name"),px+8*density,py-8*density,paint);}
}
public boolean onTouchEvent(MotionEvent event){scale.onTouchEvent(event);if(event.getActionMasked()==MotionEvent.ACTION_DOWN){lastX=event.getX();lastY=event.getY();getParent().requestDisallowInterceptTouchEvent(true);return true;}if(event.getActionMasked()==MotionEvent.ACTION_MOVE){if(!scale.isInProgress()){float unit=getWidth()/360f*zoom;lon=Math.max(-180,Math.min(180,lon-(event.getX()-lastX)/unit));lat=Math.max(-90,Math.min(90,lat+(event.getY()-lastY)/unit));invalidate();}lastX=event.getX();lastY=event.getY();return true;}if(event.getActionMasked()==MotionEvent.ACTION_UP||event.getActionMasked()==MotionEvent.ACTION_CANCEL){getParent().requestDisallowInterceptTouchEvent(false);performClick();}return true;}
void run(String expression){if(ready&&!closed)evaluateJavascript("if(window.ZhaoMap){"+expression+"}",null);}
void push(){run("window.ZhaoMap.setItems(JSON.parse("+JSONObject.quote(items.toString())+"));window.ZhaoMap.setTrack(JSON.parse("+JSONObject.quote(track.toString())+"));");}
void setTrack(JSONArray value){track=value==null?new JSONArray():value;push();}
void setItems(JSONArray value){items=value==null?new JSONArray():value;push();}
void reset(){run("window.ZhaoMap.fit();");}
void focus(JSONObject point){for(int i=0;i<items.length();i++){JSONObject row=items.optJSONObject(i);if(row!=null&&row.optJSONObject("position")==point){run("window.ZhaoMap.focus("+JSONObject.quote(row.optString("id"))+");");return;}}}
void resumeMap(){onResume();if(!ready&&!closed)reload();}
void pauseMap(){track=new JSONArray();setItems(new JSONArray());onPause();}
void close(){items=new JSONArray();closed=true;ready=false;stopLoading();destroy();}
public boolean onTouchEvent(MotionEvent event){if(event.getActionMasked()==MotionEvent.ACTION_DOWN)getParent().requestDisallowInterceptTouchEvent(true);if(event.getActionMasked()==MotionEvent.ACTION_UP||event.getActionMasked()==MotionEvent.ACTION_CANCEL)getParent().requestDisallowInterceptTouchEvent(false);return super.onTouchEvent(event);}
public boolean performClick(){super.performClick();return true;}
}