私はかなり検索しましたが、まったく無知ではありません。私は自分の側で一時的な解決策を実装しましたが、より良いアプローチがあるかどうか疑問に思っていました.
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 秒ごとに呼び出されるサービスがあります。このサービスは、ダッシュボード アクティビティ (緯度、経度) から静的変数にアクセスし、それをサーバーに送信します。
私の質問:
アクティビティが onPause になった場合、requestLocationUpdates 関数は停止しますか? それとも働き続けますか?
機能し続ける場合、lat と lon の 2 つの静的 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 で何も取得していません。