package com.example.gpsintent2; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.app.Activity; import android.content.Context; import android.util.Log; import android.widget.TextView; public class MainActivity extends Activity { private MyLocThread thread1; private TextView textView; private Handler viewHandler; private static final String TAG = "********************"; public class MyLocThread extends Thread { private LocationManager locationManager; private LocationHelper loc; private Handler handler; public MyLocThread() { Log.v(TAG, "------MyLocThread----"); setDaemon(true); setName("LocationThread"); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); loc = new LocationHelper( ); } public void run() { Log.v(TAG, "------run----"); Looper.prepare(); handler = new Handler(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 0f, loc ); Looper.loop(); } private void StopRequest() { // TODO 自動生成されたメソッド・スタブ if( locationManager != null){ locationManager.removeUpdates(loc); } if ( this.handler != null ){ Log.i(TAG, "looper と handler 停止処理"); this.handler.getLooper().quit(); this.handler = null; } } } public class LocationHelper implements LocationListener { private Location loc; @Override public void onLocationChanged(Location location) { // TODO 自動生成されたメソッド・スタブ Log.v(TAG, "onLocationChanged"); loc = location; viewHandler.post(new Runnable() { public void run() { textView.setText( "緯度" + loc.getLatitude() ); } }); Log.i("Latitude", String.valueOf(location.getLatitude())); Log.i("Longitude", String.valueOf(location.getLongitude())); Log.i("Accuracy", String.valueOf(location.getAccuracy())); Log.i("Altitude", String.valueOf(location.getAltitude())); Log.i("Time", String.valueOf(location.getTime())); Log.i("Speed", String.valueOf(location.getSpeed())); Log.i("Bearing", String.valueOf(location.getBearing())); } @Override public void onProviderDisabled(String arg0) { // TODO 自動生成されたメソッド・スタブ Log.v(TAG, "onProviderDisabled"); } @Override public void onProviderEnabled(String arg0) { // TODO 自動生成されたメソッド・スタブ Log.v(TAG, "onProviderEnabled"); } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { // TODO 自動生成されたメソッド・スタブ Log.v(TAG, "onStatusChanged"); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.textView1); //UI を変更したい場合必要 viewHandler = new Handler(); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "onResume"); thread1 = new MyLocThread(); thread1.start(); } @Override protected void onPause() { super.onPause(); Log.i(TAG, "onPause"); // 便宜的にここで停止処理 thread1.StopRequest(); } }
2013年9月16日月曜日
別スレッドで位置情報を取得する:Android GPS Looper
関連記事
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿