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

89 lines
6.9 KiB
Java
Raw Normal View History

package cn.ucvl.zhaodisplay;
import android.app.*;
import android.content.*;
import android.os.*;
import android.location.*;
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. */
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;
final Handler ui=new Handler();
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();
}
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);
}
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(active||stopping||starting)return START_NOT_STICKY;
starting=true;busy=true;
final String receipt=prefs.getString("receipt","");
notification("正在确认本人的共享授权");
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;
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);
}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);}
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";
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);
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();}
}
void stopSharing(){
if(stopping)return;stopping=true;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);
}
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();}
}