我发布了我的要求,问题和代码,我不知道我的代码有什么问题,任何帮助..
我的要求:我希望每10分钟从GPS获得一次纬度,经度
问题:我继续获得纬度,经度
我的代码:
1]。我在活动中使用此代码,我正在从活动中启动广播接收器
//Pending Intent
Intent in = new Intent(this,GPSReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, in, 0);
//Alaram manager
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
am.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 10*60*1000, pi);
2] .BroadCast Class“GPSReceiver.class”,从这里我开始服务名称为GPSService
public class GPSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context,GPSService.class);
context.startService(service);
}
}
3]。服务类“GPSService”,用于获取位置更新
public class GPSService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
//Flag to know GPS Status
boolean isGPSEnabled = false;
LocationManager locationmanager;
String locationgpsprovider = LocationManager.GPS_PROVIDER;
double latitude;
double longtitude;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//To get Location service
locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
//To get GPS Status
isGPSEnabled = locationmanager.isProviderEnabled(locationgpsprovider);
if (!isGPSEnabled) {
Toast.makeText(this, "Please check your GPS connection", Toast.LENGTH_LONG).show();
}else {
locationmanager.requestLocationUpdates(locationgpsprovider, 0, 0, ll);
}
return START_NOT_STICKY;
}
LocationListener ll = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
Log.i("Hei", "10 minutes up");
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
};
答案 0 :(得分:0)
每当你发出警报时,它会向服务提供另一个意图,并且位置管理员会重新开始。由于LocationManager已按指定的时间间隔交付位置,因此您不需要在此处发出警报。
只需启动您的服务一次,并在onCreate
实例化您的位置管理员资料。在这种情况下,仅将onStartCommand
用于return START_NOT_STICKY
。
提示1:定义停止服务的条件,不要让它永远运行。
提示2:请查看requestLocationUpdates javadoc以设置正确的minTime
。
提示3:您可以在Android文档中找到更多提示: http://developer.android.com/training/location/index.html