Files
ucvl-home-vision/android-display/src/cn/ucvl/zhaodisplay/LocationService.java
T

144 lines
14 KiB
Java
Raw Normal View History

package cn.ucvl.zhaodisplay;
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 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="",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);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.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||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;notification("正在确认本人的共享授权");
worker.execute(()->{try{
JSONObject result=DisplayApi.call("/api/location/update",sessionToken,new JSONObject().put("action","start").put("consent",true).put("receipt",prefs.getString("receipt","")).put("bufferedHistory",true));
if(stopping||destroyed)return;
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,sampleSeconds*1000L,0,this);}
catch(SecurityException e){prefs.edit().putString("status","定位权限未开启").apply();}
}
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{
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;
}
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("网络或同步暂未完成,手机轨迹已保留,恢复后自动补传");}
}
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;starting=false;busy=true;active=false;latest=null;
try{manager.removeUpdates(this);}catch(Exception ignored){}
prefs.edit().putBoolean("active",false).putString("status","本机已停止采集,联网后通知平台清除当前位置;关闭前轨迹仍会补传").apply();notification("已停止定位 · 联网后完成同步");nextAttempt=0;
}
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 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){}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();
}
}