如果不是太適合你,爲什麼不使用谷歌的定位服務嘗試:
上app.gradle:
compile 'com.google.android.gms:play-services-location:9.0.2'
和活動:
locationRequest = new LocationRequest()
.setFastestInterval(5000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(10);
GoogleApiClient.Builder clientBuilder = new GoogleApiClient.Builder(ActivityName.this)
.addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.e(TAG,"API CLIENT CONNECTED");
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
Log.e(TAG,"API CLIENT SUSPENDED");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.e(TAG,"API CLIENT CONNECTION FAILED");
}
});
apiClient= clientBuilder.build();
apiClient.connect();
,這是位置更新的開始,谷歌客戶端連接後:
void startLocationUpdates(){
if(apiClient!=null && apiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, ActivityName.this);
Log.e(TAG, "Location Updates started");
}
}
也確保活動實現LocationListener的,這樣就可以聽到您的位置更新:
@Override
public void onLocationChanged(Location updatedLocation) {
Log.e(TAG,"LOCATIONUPDATE: "+updatedLocation.toString());
}
我已經在使用它,但是當d evice閒置不更新.... –
如果你需要的設備永遠醒着,看看激活鎖定策略從https://developer.android.com/training/scheduling/wakelock.html – MetaSnarf
是,metasnarf加上wakelock將解決問題...謝謝你們 –