この記事は最終更新日から1年以上経過しています。
クラス直下で宣言
1 | private PendingIntent pi; |
2 | LocationManager mLocationManager; |
3 | ReceiveLocation receiver; |
onCreate内に以下を記述
1 | mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); |
2 | receiver = new ReceiveLocation(); |
5 | final IntentFilter filter = new IntentFilter(); |
6 | filter.addAction( "com.android.practice.ACTION_LOCATION_UPDATE" ); |
7 | registerReceiver(receiver, filter); |
onResume内に以下を記述
2 | final Intent nextIntent = new Intent(); |
3 | nextIntent.setAction( "com.android.practice.ACTION_LOCATION_UPDATE" ); |
5 | pi = PendingIntent.getBroadcast( this , 0 , nextIntent, PendingIntent.FLAG_UPDATE_CURRENT); |
6 | mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 , 0 , pi); |
onPause、もしくはonDestroyに以下が必要
1 | mLocationManager.removeUpdates(pi); |
onDestroyに以下が必要
1 | unregisterReceiver(receiver); |
通知を受け取るブロードキャストを作成
1 | class ReceiveLocation extends BroadcastReceiver{ |
3 | public void onReceive(Context context, Intent intent) { |
4 | if (intent.hasExtra(LocationManager.KEY_LOCATION_CHANGED)){ |
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(); |
これは必要なのかわかりませんが、念のため
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/