里面我读了很多的问题,在这里,但无法弄清楚是什么问题。与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