我在这里阅读了很多问题,但无法弄清问题是什么.
我正在为Android编写一个现场服务应用程序.在其中一个活动(MyActivity.java)中,我有两个按钮:Start和Stop.
当现场工作人员按下启动时,我需要使用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 Lat: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);
它说BEST PROVIDER是: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);
首先,这是一个很好的方法吗?如果是,请检查我错过了什么.如果不是,请告诉我如何才能更好地实现这一点?
谢谢.:)