私は Android チュートリアルを Geofences で使用しましたが、これは明らかに、アプリが閉じているときには機能しません。そのため、検索した後、SOのユーザーb-ryceがBroadcastReceiverを使用しているため、アプリがアクティブでない場合でもジオフェンスがトリガーされることに気付きました(彼のSOの質問へのリンク)。
登録された場所の外側/内側に移動したときに、ジオフェンスを強制的にトリガーすることはできません。これが私の手順です:
/**
* GeoLocation library
*/
mGeoLocation = new GeoLocation(sInstance);
/**
* mReceiver init
*/
mReceiver = new Receiver();
sInstance.registerReceiver(mReceiver, mReceiver.createIntentFilter());
GeoLocation クラス内:
/*
* Create a PendingIntent that triggers an IntentService in your
* app when a geofence transition occurs.
*/
protected PendingIntent getTransitionPendingIntent() {
if (mGeoPendingIntent != null) {
return mGeoPendingIntent;
}
else {
// Create an explicit Intent
// Intent intent = new Intent(mContext,
// ReceiveTransitionsIntentService.class);
Intent intent = new Intent(getClass().getPackage().getName() + ".GEOFENCE_RECEIVE");
/**
* Return the PendingIntent
*/
return PendingIntent.getBroadcast(
mContext,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
新しいジオフェンスを作成する方法は次のとおりです。
Geofence fence = new Geofence.Builder()
.setRequestId(hashCode)
// when entering this geofence
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(
Double.parseDouble(single.getSetting("latitude")),
Double.parseDouble(single.getSetting("longitude")),
Float.parseFloat(single.getSetting("radius")) // radius in meters
)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
mGeofences.add(fence);
配列にデータが入力され、Geofence クラス内で AddGeofences メソッドを呼び出します
mGeoLocation.AddGeofences(mGeofences);
受信者クラスの AndroidManifest.xml:
<!-- RECEIVER -->
<receiver android:name=".Receiver" >
</receiver>
また、Receiver クラスは、ジオフェンスがトリガーされたときにログに記録する必要があります。
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("sfen", "Broadcast recieved "+ action +" but not needed.");
}
問題は、場所を選択するアプリ内でマップを開いたときにのみジオフェンスがトリガーされることです。アプリを閉じる (バックグラウンドで実行する) と、何もトリガーされず、ジオフェンス遷移も何もトリガーされません。
誰かが私が間違っていることを教えてもらえますか?