Release 0.1.45: member phone locations and people-first family navigation

This commit is contained in:
Codex
2026-10-18 21:26:12 +08:00
parent 3b2c046060
commit fdb239b3ed
47 changed files with 914 additions and 287 deletions
@@ -2,7 +2,7 @@ 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).getString("token","").isEmpty())
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));
}
}
@@ -5,57 +5,118 @@ import android.os.*;
import android.content.*;
import android.content.pm.PackageManager;
import android.Manifest;
import android.view.View;
import android.widget.*;
import android.text.InputType;
import org.json.JSONObject;
import org.json.*;
import java.util.*;
/** Phone-only, explicit opt-in. The TV never requests location permission. */
/** Paired member identity, family viewing and voluntary sharing; no account or display UI. */
public class LocationActivity extends Activity {
static volatile boolean pairing=false;
TextView status; EditText code; Button pair,start,stop; CheckBox consent;
TextView identity,status,viewStatus;EditText code;Button pair,reload;
CheckBox consent;Switch sharing;Spinner cadence;LinearLayout settings,recipients,familyList;
LocationMapView map;boolean rendering=false,visible=false,loading=false,settingsReady=false,pendingStart=false;
int generation=0,settingsRequest=0;long lastList=0;String settingsReceipt="",settingsError="";
final Map<String,List<CheckBox>> choices=new HashMap<>();
android.content.SharedPreferences prefs;
final Handler ui=new Handler();
final Runnable refresh=new Runnable(){public void run(){render();ui.postDelayed(this,2000);}};
final Runnable refresh=new Runnable(){public void run(){if(!visible)return;render();if(SystemClock.elapsedRealtime()-lastList>15000)loadFamily();ui.postDelayed(this,2000);}};
TextView text(String value,int size,LinearLayout parent){TextView t=new TextView(this);t.setText(value);t.setTextSize(size);t.setTextColor(0xff263e35);t.setPadding(0,12,0,12);parent.addView(t);return t;}
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);
LinearLayout layout=new LinearLayout(this);layout.setOrientation(1);int p=(int)(24*getResources().getDisplayMetrics().density);layout.setPadding(p,p,p,p);layout.setBackgroundColor(0xfff5f2e9);
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){
prefs.edit().putBoolean("active",false).putString("status","共享已中断,请本人重新开启").apply();
startService(new Intent(this,LocationService.class).setAction("STOP"));
}
LinearLayout layout=new LinearLayout(this);layout.setOrientation(1);int p=(int)(20*getResources().getDisplayMetrics().density);layout.setPadding(p,p,p,p);layout.setBackgroundColor(0xfff5f2e9);
ScrollView scroll=new ScrollView(this);scroll.addView(layout);setContentView(scroll);
TextView heading=new TextView(this);heading.setText("家人位置共享");heading.setTextSize(28);layout.addView(heading);
TextView help=new TextView(this);help.setText("不需要注册或登录。请家人从平台的家庭成员中选择你的档案,生成手机配对码。\n\n配对后核对你的姓名、家庭及允许查看的人。只有你同意并开启共享,才约每 5 分钟上传最新位置。通知栏可随时停止;不保存轨迹。断网或省电可能延迟更新。");help.setTextSize(16);help.setPadding(0,p,0,p);layout.addView(help);
status=new TextView(this);status.setTextSize(17);layout.addView(status);
code=new EditText(this);code.setHint("输入家人为你生成的八位配对码");code.setInputType(InputType.TYPE_CLASS_NUMBER);code.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(8)});layout.addView(code);
pair=new Button(this);pair.setText("绑定我的位置共享");layout.addView(pair);pair.setOnClickListener(v->pair());
consent=new CheckBox(this);consent.setText("我已核对上方的本人姓名、家庭、查看名单及有效期,同意开启位置共享。关闭后停止采集并清除位置。");layout.addView(consent);
start=new Button(this);start.setText("同意并开启定位");layout.addView(start);start.setOnClickListener(v->start());
stop=new Button(this);stop.setText("停止共享并清除位置");layout.addView(stop);stop.setOnClickListener(v->{startService(new Intent(this,LocationService.class).setAction("STOP"));consent.setChecked(false);});
render();ui.post(refresh);
text("家人位置",30,layout);identity=text("",17,layout);
text("只显示家人主动授权给这台手机的位置。查看家人不需要开启自己的定位。",16,layout);
button("我的位置设置",layout).setOnClickListener(v->{settings.setVisibility(settings.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);if(settings.getVisibility()==View.VISIBLE)loadSettings();});
status=text("",16,layout);
settings=new LinearLayout(this);settings.setOrientation(1);layout.addView(settings);
text("配对本人 · 无需注册或登录",22,settings);
text("请家人在平台进入家庭总览 → 为家庭成员配对手机,选择你的成员档案。这里使用手机配对码,不使用显示终端配对码。",16,settings);
code=new EditText(this);code.setHint("八位手机配对码");code.setInputType(InputType.TYPE_CLASS_NUMBER);code.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(8)});settings.addView(code);
pair=button("配对我的手机",settings);pair.setOnClickListener(v->pair());
text("我的位置共享",22,settings);text("选择谁能看我的位置",16,settings);
recipients=new LinearLayout(this);recipients.setOrientation(1);settings.addView(recipients);
text("上传频率",16,settings);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);settings.addView(cadence);
text("实时档更耗电和流量;更新受信号、网络与系统省电影响。调整名单或频率前,先关闭共享。",14,settings);
consent=new CheckBox(this);consent.setText("我已核对本人身份、有效期和所选查看人,同意按上述频率共享位置。关闭后停止采集并清除位置。");settings.addView(consent);
sharing=new Switch(this);sharing.setText("共享我的位置");sharing.setTextSize(20);sharing.setPadding(0,20,0,20);settings.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();});
button("打开手机系统定位设置",settings).setOnClickListener(v->startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)));
settings.setVisibility(prefs.getString("token","").isEmpty()?View.VISIBLE:View.GONE);
text("家人现在的位置",22,layout);viewStatus=text("",16,layout);
map=new LocationMapView(this);layout.addView(map,new LinearLayout.LayoutParams(-1,(int)(260*getResources().getDisplayMetrics().density)));
text("世界位置概览 · 可拖动、双指缩放;点家人卡片定位。底图为本地陆地轮廓,不含道路。",13,layout);
button("查看全部位置",layout).setOnClickListener(v->map.reset());
reload=button("刷新家人位置",layout);reload.setOnClickListener(v->loadFamily());
familyList=new LinearLayout(this);familyList.setOrientation(1);layout.addView(familyList);render();
}
void render(){
boolean paired=!prefs.getString("token","").isEmpty(),active=prefs.getBoolean("active",false);
boolean paired=!prefs.getString("token","").isEmpty(),active=prefs.getBoolean("active",false),busy=pairing||LocationService.busy;
long expires=prefs.getLong("expires",0);
status.setText("成员:"+prefs.getString("memberName","尚未绑定")+"\n允许查看:"+prefs.getString("recipients","无")+"\n家庭:"+prefs.getString("home","尚未绑定")+"\n"+(expires>0?"有效期至 "+java.text.DateFormat.getDateTimeInstance().format(new java.util.Date(expires))+"\n":"")+prefs.getString("status","共享关闭"));
boolean busy=pairing||LocationService.busy;
start.setEnabled(paired&&!active&&!busy);stop.setEnabled(paired&&!pairing);pair.setEnabled(!active&&!busy);consent.setEnabled(!active&&!busy);
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);
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);
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();
}
void pair(){
if(pairing||LocationService.busy||prefs.getBoolean("active",false))return;
String value=code.getText().toString().trim();if(!value.matches("[0-9]{8}")){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",2));
StringBuilder viewers=new StringBuilder();for(String type:new String[]{"viewers","displays"}){org.json.JSONArray list=response.getJSONArray(type);for(int i=0;i<list.length();i++){if(viewers.length()>0)viewers.append("、");viewers.append(list.getJSONObject(i).getString("name"));if(type.equals("displays"))viewers.append("(公共显示终端)");}}
prefs.edit().putString("memberName",response.getString("memberName")).putString("receipt",response.getString("receipt")).putString("recipients",viewers.toString()).putString("token",response.getString("token")).putString("home",response.getString("home")).putLong("expires",(long)(response.getDouble("expires")*1000)).putBoolean("active",false).putString("status","已绑定,尚未开启定位").apply();
runOnUiThread(()->{code.setText("");consent.setChecked(false);render();});
}catch(Exception e){runOnUiThread(()->Toast.makeText(this,"绑定未成功,请检查网络或重新获取配对码",1).show());}finally{pairing=false;runOnUiThread(this::render);}},"location-pair").start();
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();
runOnUiThread(()->{if(isDestroyed())return;pairing=false;generation++;loading=false;familyList.removeAllViews();map.setItems(new JSONArray());code.setText("");consent.setChecked(false);settingsReady=false;loadSettings();loadFamily();});
}catch(Exception e){runOnUiThread(()->{if(!isDestroyed())Toast.makeText(this,"配对未成功,请检查手机配对码或安装新版 App",1).show();});}finally{pairing=false;runOnUiThread(()->{if(!isDestroyed())render();});}},"location-pair").start();
}
void loadFamily(){
String token=prefs.getString("token","");if(!visible||loading||token.isEmpty())return;
int g=generation;loading=true;lastList=SystemClock.elapsedRealtime();render();
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);});}
});
}catch(Exception e){runOnUiThread(()->{if(!visible||g!=generation)return;familyList.removeAllViews();map.setItems(new JSONArray());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();
new Thread(()->{try{
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();});
}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))return;
if(!consent.isChecked()){Toast.makeText(this,"请本人阅读并勾选共享说明",1).show();return;}
if(pairing||LocationService.busy||prefs.getBoolean("active",false)||!settingsReady)return;
if(!consent.isChecked()){Toast.makeText(this,"请本人核对并勾选共享说明",1).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;}
LocationService.busy=true;render();
try{startForegroundService(new Intent(this,LocationService.class).setAction("START"));}
catch(Exception e){LocationService.busy=false;render();Toast.makeText(this,"无法启动共享,请保持本页面在前台后重试",1).show();}
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 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)start();else Toast.makeText(this,"未开启定位权限,不采集位置",1).show();}}
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;lastList=0;if(!settingsReady)loadSettings();ui.post(refresh);if(pendingStart){pendingStart=false;start();}}
public void onPause(){visible=false;generation++;loading=false;ui.removeCallbacksAndMessages(null);if(map!=null)map.setItems(new JSONArray());if(familyList!=null)familyList.removeAllViews();super.onPause();}
public void onDestroy(){ui.removeCallbacksAndMessages(null);super.onDestroy();}
}
@@ -0,0 +1,9 @@
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 boolean due(long now,long lastAttempt,int interval,boolean firstFix){
return lastAttempt==0||now-lastAttempt>=1000L*(firstFix?10:seconds(interval));
}
}
@@ -0,0 +1,31 @@
package cn.ucvl.zhaodisplay;
import android.content.Context;
import android.graphics.*;
import android.view.*;
import org.json.*;
import java.io.*;
import java.util.*;
/** 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;}});
}
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;}
public boolean performClick(){super.performClick();return true;}
}
@@ -16,6 +16,7 @@ public class LocationService extends Service implements LocationListener {
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="";
final Handler ui=new Handler();
public void onCreate(){
super.onCreate();prefs=getSharedPreferences("location",0);manager=(LocationManager)getSystemService(LOCATION_SERVICE);
@@ -40,33 +41,44 @@ public class LocationService extends Service implements LocationListener {
worker.execute(()->{try{
JSONObject r=DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","start").put("consent",true).put("receipt",receipt));
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,300,TimeUnit.SECONDS);
worker.scheduleWithFixedDelay(this::upload,1,10,TimeUnit.SECONDS);
}catch(Exception e){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,300000,0,this);}
try{for(String provider:new String[]{LocationManager.GPS_PROVIDER,LocationManager.NETWORK_PROVIDER})if(manager.getAllProviders().contains(provider))manager.requestLocationUpdates(provider,intervalSeconds*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;}
try{
String signal=checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED||checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED?manager.isLocationEnabled()?"waiting":"location_disabled":"permission_denied";
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";
}
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();}
}
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 stopSharing(){
if(stopping)return;stopping=true;busy=true;active=false;latest=null;
try{manager.removeUpdates(this);}catch(Exception ignored){}
@@ -28,6 +28,7 @@ public class MainActivity extends Activity {
final Runnable themeTick=new Runnable(){public void run(){applyTimeMode();themeHandler.postDelayed(this,60000);}};
@Override public void onCreate(Bundle state) {
super.onCreate(state);
getSharedPreferences("display",0).edit().putBoolean("phoneMode",false).apply();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
immersive();
web=new WebView(this);