カテゴリー
SugiBlog Webエンジニアのためのお役立ちTips

位置情報を更新し、通知を出す

この記事は最終更新日から1年以上経過しています。

クラス直下で宣言

1private PendingIntent pi;
2LocationManager mLocationManager;
3ReceiveLocation receiver;

onCreate内に以下を記述

1mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
2receiver = new ReceiveLocation();
3 
4//指定したIntentに反応するようにReceiverにIntentFilterを登録
5final IntentFilter filter = new IntentFilter();
6filter.addAction("com.android.practice.ACTION_LOCATION_UPDATE");
7registerReceiver(receiver, filter);


onResume内に以下を記述

1//Intentを作成
2final Intent nextIntent = new Intent();
3nextIntent.setAction("com.android.practice.ACTION_LOCATION_UPDATE");
4 
5pi = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
6mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, pi);

onPause、もしくはonDestroyに以下が必要

1mLocationManager.removeUpdates(pi);

onDestroyに以下が必要

通知を受け取るブロードキャストを作成

1class ReceiveLocation extends BroadcastReceiver{
2  @Override
3  public void onReceive(Context context, Intent intent) {
4    if(intent.hasExtra(LocationManager.KEY_LOCATION_CHANGED)){
5      LocationManager lm =
6        (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
7      Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
8      String message = "Location\n"
9        + "Longitude:" + location.getLongitude() + "\n"
10        + "Latitude:" + location.getLatitude();
11      Toast.makeText(context, message, Toast.LENGTH_LONG).show();
12    }
13  }
14}

これは必要なのかわかりませんが、念のため
AndroidManifest.xmlのapplicationタグ内に記述します。

1<receiver android:name="com.android.practice.LocationUpdateReceiver"/>

参考URL
http://d.hatena.ne.jp/sei10sa10/20110720/1311168936
http://techbooster.org/android/application/2525/

この記事がお役に立ちましたらシェアお願いします
3,531 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です