我已经搜索了很多,但我并不是完全一无所知。我已经实施了一个临时解决方案,但想知道是否有更好的方法。
我有一个应用程序每 60 秒将一个人的位置发送到服务器。在我的仪表板上(应用程序启动后将转到onPause的主屏幕),我使用以下代码注册了一个LocationManager :
service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else
{
Criteria criteria = new Criteria();
provider = service.getBestProvider(criteria, false);
service.requestLocationUpdates(provider, 10000, 50, this);
Location location = service.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null)
{
onLocationChanged(location);
}
else
{
Log.d("Location: ", "No update received");
}
}
然而,正如我所提到的,这个活动将被用户最小化(通过按下主页按钮)。AlarmManager 每 60 秒调用一次服务。该服务从仪表板活动(纬度、经度)访问静态变量并将其发送到服务器。
我的问题:
如果活动继续暂停,requestLocationUpdates 函数会停止吗?还是会继续工作?
如果它继续工作,它将不断更新两个 lat 和 lon 静态 String 对象,并且服务将不断获取更新的值。如果它们停止,服务将一次又一次地获取相同的旧值。
另外,有没有更好的方法来解决这个问题?混合使用 GPS 提供商和网络提供商?(我需要相当准确的值)。
编辑
这是我的闹钟。此代码在登录活动中
Intent i = new Intent(con, LocationPoller.class);
i.putExtra(LocationPoller.EXTRA_INTENT, new Intent(con,
Login.class));
i.putExtra(LocationPoller.EXTRA_PROVIDER,
LocationManager.GPS_PROVIDER);
gps = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(con, 0, i, 0);
gps.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
10 * 1000, pi);
Log.d("Service: ",
"GPS Service started and scheduled with AlarmManager");
这是我的接收器(也在登录活动中)
private class ReceiveMessages extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Location loc = (Location) intent.getExtras().get(
LocationPoller.EXTRA_LOCATION);
String msg;
if (loc == null)
{
msg = intent.getStringExtra(LocationPoller.EXTRA_ERROR);
}
else
{
msg = loc.toString();
}
if (msg == null)
{
msg = "Invalid broadcast received!";
}
Log.d("GPS Broadcast: ", msg);
}
}
什么都没有发生:s 在 logcat 上没有得到任何东西,这意味着没有收到广播。