裏面我讀了很多的問題,在這裏,但無法弄清楚是什麼問題。與AlarmManager的Android定期GPS位置更新服務
我正在寫爲Android現場服務應用程序。在其中一個活動(MyActivity.java)中,我有兩個按鈕:開始和停止。
當現場工作人員按下啓動,我需要與GPS讓他當前的位置,並將其發送到及時區間服務器(說爲5分鐘默認情況下,在這裏我將它設置爲20秒。用於測試)。客戶希望看到工人在交通上花費多少時間,我的城市(伊斯坦布爾)的交通情況很糟糕。
我在我的活動中有一個AlarmManager,當按下開始按鈕時,報警設置爲AlarmManager.setRepeating()
以啓動服務(ServiceClass.java)。
Intent intent = new Intent (MyActivity.this, ServiceClass.class);
mPendingIntent = PendingIntent.getService(MyActivity.this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mAlarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 20*1000,
mPendingIntent);
我用停止按鈕取消報警。
它完美到這裏,在服務啓動。它的onCreate()
,onStart()
和onDestroy()
方法被執行。但我無法獲得位置。我沒有在真正的設備上工作,所以我使用DDMS發送位置信息。但是該應用程序跳過該步驟並將我的位置的經度和緯度打印爲Lon:0緯度:0。
這裏的服務裏面的代碼:
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("Testing", "Service got started, calling location updates:");
mLocationManager.requestSingleUpdate(mCriteria, mLocationListener,
getMainLooper());
Log.i("TESTING LOCATION UPDATE: LOCATION:", "\nLat:" + mLatitude +
" Lon:" + mLongitude);
stopSelf(startId);
Log.d("Testing", "Service Stopped!");
最後,這裏是我的LocationListener的:
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if(location != null){
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
Log.i("onLocationChanged(Location location)", "Lat:"+mLatitude + "
Lon:" + mLongitude);
}
也是東西引起了我的眼睛,當我運行代碼:
mLocationProvider = mLocationManager.getBestProvider(mCriteria, true);
Log.i("BEST PROVIDER IS:", mLocationProvider);
它說最好的供應商是:gps。但是這個日誌裏面onProviderEnabled()從來沒有顯示在logcat中。
@Override
public void onProviderEnabled(String s) {
Log.v("onProviderEnabled", "ENABLED");
}
兩件事情的添加,如果我使用:
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mLocationListener);
它也不起作用。
然而,這工作,我可以得到LastKnownLocation:
Location lastKnown = mLocationManager.getLastKnownLocation(
LocationManager.GPS_PROVIDER);
首先,這是這樣做的一個好方法?如果是這樣,請檢查我的缺失。如果不是,你能告訴我怎樣才能更好地實現這一點?
謝謝。 :)
在Android的位置更好的文章之一; http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html - 它解決了你的問題 – tonys 2012-03-26 09:55:21
@tonys感謝東尼斯最,我會讀的是第一件事情。 – Lev 2012-03-26 12:47:28
這完美的作品:[請在此輸入鏈接的描述(http://stackoverflow.com/questions/21762293/run-gps-as-background-service-and-send-coordinates-to-web-server-php) – 2016-12-18 08:57:53