2

我是 android 开发的新手,我希望我的设备在后台模式下每 40 秒获取一次 GPS 位置,即使在应用程序被杀死之后也是如此。为此,在 MyAlarm.class 中,我设置了每 40 秒重复一次警报,以使用待定意图调用“RepeatingAlarm.class(扩展 BroadcastReceiver)”。在每 40 秒调用一次的“RepeatingAlarm.class”的 onReceive 方法中,我创建了另一个挂起的意图来调用 MyReceiver.class(它扩展了 BroadcastReceiver)。我已将在“RepeatingAlarm.class”中创建的待处理意图传递给 requestLocationUpdate 函数,以获取 GPS 位置。

我的问题是,有时我会每 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 每隔几秒就会频繁调用一次。请帮助我提供一些示例代码行来解决此问题。谢谢你们。

4

1 回答 1

0

根据开发人员文档requestSingleUpdate()方法“使用命名提供者和待定意图注册单个位置更新。”

您需要改用requestLocationUpdates()方法。

此方法的第二个参数minimum time interval between location updates, in milliseconds将允许您一次又一次地获取位置。

于 2014-04-10T11:48:26.110 回答