以下服务优雅地为我提供位置服务的准确性和状态。在我登录应用程序之前使用此服务,因为应用程序需要启用位置服务。
基于此服务输入,您可以
- 提示用户开启定位功能
- 一旦接收到位置,就可以启动地图
- 如果位置断开连接,请处理其余逻辑
位置更新要记住的重要一点是
-
指定最小距离变化以接收更新
setSmallestDisplacement(即使我们在一个位置长时间不动,API 也会返回数据)
-
设置 FastestInterval 以接收位置更新
-
设置优先级参数
setPriority根据您的要求
public class AppLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private Context appContext;
private boolean currentlyProcessingLocation = false;
private int mInterval=0;
private final int CONNTIMEOUT=50000;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
appContext=getBaseContext();
Toast.makeText(getBaseContext(), "Location Service Started", Toast.LENGTH_SHORT)
.show();
if(intent != null){
mInterval = intent.getIntExtra(Constants.REFRESHTIMETAG, 5);
mIMEI = intent.getStringExtra(Constants.IMEITAG);
Log.v(Constants.BLL_LOG, "AppLocationService onStartCommand , mInterval=" + mInterval + " | mIMEI=" + mIMEI);
}
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_STICKY;
}
private void startTracking() {
Log.v(Constants.BLL_LOG, "startTracking");
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
Log.v(Constants.BLL_LOG, "ConnectionResult SUCCESS");
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (!googleApiClient.isConnected() || !googleApiClient.isConnecting()) {
googleApiClient.connect();
Log.v(Constants.BLL_LOG, "googleApiClient.connect()");
}else{
Log.v(Constants.BLL_LOG, "NOT connected googleApiClient.connect()");
//
//INTIMATE UI WITH EITHER HANDLER OR RUNONUI THREAD
//
}
} else {
Log.v(Constants.BLL_LOG, "unable to connect to google play services.");
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public AppLocationService() {
}
@Override
public void onConnected(Bundle bundle) {
Log.v(Constants.BLL_LOG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(mInterval * 1000); // milliseconds
locationRequest.setFastestInterval(mInterval * 1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(MIN_DISTANCE_CHANGE_FOR_UPDATES);//distance change
int permissionCheck = ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck!= PackageManager.PERMISSION_DENIED)
{ LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(appContext, "Location Service got connected", Toast.LENGTH_SHORT)
.show();
}
});
}
@Override
public void onConnectionSuspended(int i) {
Log.v(Constants.BLL_LOG, "onConnectionSuspended");
//INTIMATE UI ABOUT DISCONNECTION STATUS
}
@Override
public void onLocationChanged(Location location) {
Log.v(Constants.BLL_LOG, "onLocationChanged position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
//if (location.getAccuracy() < 500.0f)
Log.v(Constants.BLL_LOG, "onLocationChanged position: location.getAccuracy()= "+location.getAccuracy());
//DO YOUR BUSINESS LOGIC, FOR ME THE SAME WAS TO SEND TO SERVER
sendLocationDataToWebsite(location);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.v(Constants.BLL_LOG, "onConnectionFailed");
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(appContext, "Location Service got disconnected temporarily", Toast.LENGTH_SHORT)
.show();
}
});
}
/**
* Send details to server
* @param location
*/
void sendLocationDataToWebsite(Location location){
}
@Override
public void onDestroy() {
super.onDestroy();
if (googleApiClient != null && googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
this.unregisterReceiver(this.batteryInfoReceiver);
}
}
注意:此服务仍需在更新版本中进行测试