SECTION149 位置情報取得時にインテントを発行する
ReceiveActivityが複数起動してしまうのが困るな。
Main.java
package com.efolab.s149; import android.app.Activity; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.location.Criteria; import android.location.LocationManager; import android.os.Bundle; import android.widget.LinearLayout; public class Main extends Activity { Context context; LinearLayout base; LocationManager loc; PendingIntent pending; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); base = new LinearLayout(context); base.setOrientation(LinearLayout.VERTICAL); setContentView(base); //位置情報取得時に実行するインテントを生成 Intent intent = new Intent(context, ReceiveActivity.class); // intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); //効果なし pending = PendingIntent.getActivity(context, 0, intent, 0); //精度を設定 Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); //LocationManagerインスタンスを生成 loc = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); //位置情報をリクエスト loc.requestLocationUpdates(3L, 0, criteria, pending); } @Override protected void onDestroy(){ super.onDestroy(); loc.removeUpdates(pending); } }
ReceiveActivity.java
package com.efolab.s149; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.widget.LinearLayout; import android.widget.TextView; public class ReceiveActivity extends Activity { Context context; LinearLayout base; TextView tv; private static int classCounter = 0; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); context = getApplicationContext(); base = new LinearLayout(context); setContentView(base); tv = new TextView(context); base.addView(tv); //受け取ったIntentを取得 Intent intent = getIntent(); showData(intent); } @Override protected void onNewIntent(Intent intent) { // TODO Auto-generated method stub super.onNewIntent(intent); showData(intent); } private void showData(Intent intent){ //インテントからBundleを取得 Bundle bundle = intent.getExtras(); //Locationオブジェクトを取得 Location location = (Location)bundle.get("location"); double lat = location.getLatitude(); double lng = location.getLongitude(); Log.v("ReceiveActivity","lat="+lat+",lng="+lng); tv.setText("ReceiveActivity:"+classCounter++); } }