一、应用场景
app采集定位的服务已经被广泛应用到了各种场景,随之而来的是涉及到的个人隐私问题,很多用户都会比较抵触。
但是仍然有很多场景需要定位服务,一种比如导航这类用户自发需求,一种比如危化品监测这种需要对用户有强监管。
二、采用技术
我们需要一个高德地图SDK来定时获取定位
还需要一个Service来保活。
就需要引入以下依赖
implementation ‘com.xdandroid:hellodaemon:+‘ //保活服务
implementation ‘com.amap.api:location:latest.integration‘ //高德API
三、实现
在AndoridMainfest.xml中注册一个服务
<service android:priority="1000" android:name="com.plat.cityManage.KeepService">
</service>
一下为KeepService具体内容,设定为60s向后台传送一次定位。
package com.plat.cityManage;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.plat.cityManage.utils.HttpUtils;
import com.plat.cityManage.utils.OkhttpUtils;
import com.plat.cityManage.utils.SharedPreferencesUtil;
import com.plat.cityManage.utils.StringUtil;
import com.xdandroid.hellodaemon.AbsWorkService;
import java.io.IOException;
import java.util.HashMap;
import java.util.TimerTask;
import okhttp3.Response;
public class KeepService extends AbsWorkService {
private Boolean isRunning = false;
public static Boolean isStop = false;
java.util.Timer timer = new java.util.Timer(true);
private AMapLocationClientOption locationOption = new AMapLocationClientOption();
private AMapLocationClient locationClient = null;
private String TAG = KeepService.class.getName();
public void stopService() {
try {
isRunning = false;
//AbsWorkService.cancelJobAlarmSub();
Log.e(TAG,"stopService:");
}
catch (Exception e){
}
}
@Override
public Boolean shouldStopService(Intent intent, int flags, int startId) {
return isStop;
}
@Override
public void startWork(Intent intent, int flags, int startId) {
isRunning = true;
// Util.keepService = this;
locationClient = new AMapLocationClient(this.getApplicationContext());
locationClient.setLocationOption(getDefaultOption());
locationClient.setLocationListener(locationListener);
// 启动定位
if(!locationClient.isStarted())
locationClient.startLocation();
Log.e(TAG,"this="+this+" " + new java.sql.Timestamp(System.currentTimeMillis()));
try {
timer.schedule(task, 3000, 10000);
}catch (Exception e){
}
}
@Override
public void stopWork(Intent intent, int flags, int startId) {
try {
timer.cancel();
}
catch (Exception e){}
}
@Override
public Boolean isWorkRunning(Intent intent, int flags, int startId) {
return isRunning;
}
@Nullable
@Override
public IBinder onBind(Intent intent, Void alwaysNull) {
return null;
}
@Override
public void onServiceKilled(Intent rootIntent) {
try {
timer.cancel();
}
catch (Exception e){}
}
TimerTask task = new TimerTask() {
public void run() {
if(!isStop)
{
Log.e(TAG, "Timer:" + new java.sql.Timestamp(System.currentTimeMillis()));
}
}
};
private void postPosition(AMapLocation aMapLocation) {
String url = HttpUtils.url + "userPosition/post";
if(null != HttpUtils.user && StringUtil.checkBN(HttpUtils.user.getId())){
Log.e(TAG,"userid:"+ HttpUtils.user.getId() );
HashMap<String,String> paramsMap=new HashMap<>();
paramsMap.put("userid",HttpUtils.user.getId());
paramsMap.put("lng", HttpUtils.myAMapLocation.getLongitude()+"");
paramsMap.put("lat", HttpUtils.myAMapLocation.getLatitude()+"");
try {
Response response = OkhttpUtils.getInstance().
postJSON( url, paramsMap, SharedPreferencesUtil.getString( "token", "" ) );
String content = response.body().string();
Log.e(TAG,"content:"+ content );
com.alibaba.fastjson.JSONObject result = com.alibaba.fastjson.JSONObject.parseObject( content );
int code = result.getIntValue( "code" );
if(code != 200){
Log.e( TAG, "userPosition/post:" + result.get( "message" ) );
}
}catch (IOException e){
e.printStackTrace();
Log.e( TAG, "userPosition/post:" + e.getMessage() );
}
}else{
Log.e( TAG, "用户还未登录" );
}
}
private AMapLocationClientOption getDefaultOption(){
AMapLocationClientOption mOption = new AMapLocationClientOption();
mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
mOption.setGpsFirst(true);//设置GPS定位优先
mOption.setHttpTimeOut(30000);//设置网络请求超时时间
mOption.setInterval(60000);//设置定位间隔。默认为2秒
mOption.setNeedAddress(true);//设置是否返回逆地理地址信息。默认是true
mOption.setOnceLocation(false);//设置是否单次定位。默认是false
AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
mOption.setLocationCacheEnable(false); //设置是否使用缓存定位,默认为true
return mOption;
}
AMapLocationListener locationListener = new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation loc) {
if(!isStop) {
Log.e(TAG, "isStop="+isStop+" "+new java.sql.Timestamp(System.currentTimeMillis()).toString() + "==========" +
loc.getErrorCode() + "======" + loc.getLongitude() + "," + loc.getLatitude());
if (null != loc) {
if (loc.getErrorCode() == 0) {
HttpUtils.myAMapLocation = loc;
if (loc.getLongitude() != 0.0 && loc.getLatitude() != 0.0) {
new Thread(new Runnable() {
@Override
public void run() {
postPosition(loc);
}
}).start();
}else {
if (loc.getErrorCode() == 12 || loc.getErrorCode() == 13) {
Log.e(TAG,"为了获取定位,更好的为您服务,请打开GPS");
}
//定位失败时,可通过ErrCode(错误码)信息来确定失败的原因,errInfo是错误信息,详见错误码表。
Log.e( "AmapError", "location Error, ErrCode:"
+ loc.getErrorCode() + ", errInfo:"
+ loc.getErrorInfo() );
}
}
}
}
}
};
}
Application中启动Service
public class App extends Application {
private static final String TAG = "MyApplication";
@Override
public void onCreate() {
super.onCreate();
DaemonEnv.initialize(this,KeepService.class,1);
this.startService(new Intent(this,KeepService.class));
}
}
?