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()=intervalSeconds*1000L){ flushCutoff=now;prefs.edit().putLong("lastFlushAt",now).apply();forceSync=false; } for(int i=0;i=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-lastSampleSystem.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(); } }