位置情報を更新し、通知を出す
- Android
-
2011-12-05 - 更新:2011-12-14
この記事は最終更新日から1年以上経過しています。
クラス直下で宣言
private PendingIntent pi; LocationManager mLocationManager; ReceiveLocation receiver;
onCreate内に以下を記述
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
receiver = new ReceiveLocation();
//指定したIntentに反応するようにReceiverにIntentFilterを登録
final IntentFilter filter = new IntentFilter();
filter.addAction("com.android.practice.ACTION_LOCATION_UPDATE");
registerReceiver(receiver, filter);
onResume内に以下を記述
//Intentを作成
final Intent nextIntent = new Intent();
nextIntent.setAction("com.android.practice.ACTION_LOCATION_UPDATE");
pi = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, pi);
onPause、もしくはonDestroyに以下が必要
mLocationManager.removeUpdates(pi);
onDestroyに以下が必要
unregisterReceiver(receiver);
通知を受け取るブロードキャストを作成
class ReceiveLocation extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.hasExtra(LocationManager.KEY_LOCATION_CHANGED)){
LocationManager lm =
(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
String message = "Location\n"
+ "Longitude:" + location.getLongitude() + "\n"
+ "Latitude:" + location.getLatitude();
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
}
これは必要なのかわかりませんが、念のため
AndroidManifest.xmlのapplicationタグ内に記述します。
<receiver android:name="com.android.practice.LocationUpdateReceiver"/>
参考URL
http://d.hatena.ne.jp/sei10sa10/20110720/1311168936
http://techbooster.org/android/application/2525/
この記事がお役に立ちましたらシェアお願いします
3,672 views




