我是android开发的新手,我希望我的设备在后台模式下每40秒获得一次GPS定位,即使在应用程序被杀死之后也是如此。为此,在MyAlarm.class中,我让警报每隔40秒使用挂起的意图调用“RepeatingAlarm.class(扩展BroadcastReceiver)”。在每隔40秒调用一次的"RepeatingAlarm.class“的onReceive方法中,我创建了另一个挂起的意图来调用MyReceiver.class(它扩展了BroadcastReceiver)。我已经将这个在"RepeatingAlarm.class“中创建的待定意图传递给了一个requestLocationUpdate函数,以获取GPS位置。
我的问题是,有时我会得到相同的LAT值和long值,每40秒重复一次,持续大约3分钟。
然后,我的MyReceiver.class的onReceive方法每秒调用一次,而不是在接收到GPS位置后调用。我已经粘贴了我的代码在下面,请帮助我解决方案。
MyAlarm.class
public void StartAlarm(Context context)
{
AlarmManager alm=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, RepeatingAlarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
alm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 40000, pi);
}
RepeatingAlarm.class
public class RepeatingAlarm extends BroadcastReceiver
{
public static LocationManager locationManager = null;
public static PendingIntent pendingIntent = null;
@Override
public void onReceive(Context context, Intent intent)
{
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Intent intentp = new Intent(context, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, intentp, PendingIntent.FLAG_UPDATE_CURRENT);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, true);
if(provider != null)
{
locationManager.requestSingleUpdate(locationManager.GPS_PROVIDER, pendingIntent);
}
}
}
MyReceiver.class
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
String locationKey = LocationManager.KEY_LOCATION_CHANGED;
if (intent.hasExtra(locationKey))
{
Location location = (Location)intent.getExtras().get(locationKey);
double mlatitude = location.getLatitude();
double mlongitude = location.getLongitude();
if(RepeatingAlarm.locationManager != null && RepeatingAlarm.pendingIntent)
{
RepeatingAlarm.locationManager.removeUpdates(RepeatingAlarm.pendingIntent);
}
}
}
}在上面的代码中,GPS位置每40秒接收一次。但是,有时,如果一次GPS需要很长时间才能获得位置,比如15分钟,那么每隔40秒,相同的先前位置就会重复,直到大约4分钟。这是我的主要问题。
然后,MyReceiver.class每秒钟频繁调用一次。请帮助我用一些示例代码行来解决这个问题。谢谢你们所有人。
发布于 2014-04-10 19:48:26
按照developer documents requestSingleUpdate()方法“使用命名提供者和待定意图注册单一位置更新”。
您需要改用requestLocationUpdates()方法。
此方法的第二个参数minimum time interval between location updates, in milliseconds将允许您再次获取位置。
https://stackoverflow.com/questions/22987062
复制相似问题