たぼさんの部屋

いちょぼとのんびり

T201 LocationManagerをserviceとして起動。SQliteに書込み(地図とMUtilを使用)

f:id:donsuka_kk:20121207082916p:plain

MMapViwe.java

package com.efolab.t201;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.efolab._db.DbConnection;
import com.efolab._layout.Layout3;
import com.efolab._service.MLocationManager;
import com.efolab._util.MUtil;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class MMapView extends MapActivity {

	private Context context;
	private Layout3 layout;
	private final static String API_KEY = "";// kamogashira-pc
	private MapView map;
	private TextView tv0;
	private Button btn0, btn1, btn2;

	private MapController mMapController;

	// service
	MLocationManager mLocationManager;
	Intent serviceIntent;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getApplicationContext();
		layout = new Layout3(context);
		setContentView(layout);

		// controller
		tv0 = new TextView(context);
		tv0.setText("データなし");

		map = new MapView(this, API_KEY);
		map.setClickable(true);
		map.setEnabled(true);

		btn0 = new Button(context);
		btn0.setText("START");
		btn1 = new Button(context);
		btn1.setText("STOP");
		btn2 = new Button(context);
		btn2.setText("DB select");

		// layout addView
		layout.getLayoutHeader().addView(tv0);
		layout.getLayoutMain().addView(map);
		layout.getLayoutFooter().addView(btn0);
		layout.getLayoutFooter().addView(btn1);
		layout.getLayoutFooter().setGravity(Gravity.CENTER);
		layout.getLayoutFooter().addView(btn2);

		// MapController
		mMapController = map.getController();
		mMapController.setZoom(16);

		// service intent
		serviceIntent = new Intent(context, MLocationManager.class);
		
		//listener set
		btn0.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//LocationManager 開始
				//サービスの起動確認
				if(MUtil._Observer.isServiceRunning(context, MLocationManager.class) == false){
					context.startService(serviceIntent);
					
				}
			}
		});
		btn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//LocationManager 終了
				//FIXME サービスが起動していなときに実行するとエラー発生
				//サービスの起動確認
				if(MUtil._Observer.isServiceRunning(context, MLocationManager.class) == true){
					context.stopService(serviceIntent);
					
				}
			}
		});
		btn2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//DBからselect
				try{
				DbConnection conn = new DbConnection(context);
				String sql = "select * from "+DbConnection.DBTABLE +";";
				Cursor c = conn.openAndSelect(sql);
				//結果カーソルがnullかどうか確認
				if(c != null){
					//データ処理をおこなう
					Toast.makeText(context, "カーソルの件数="+c.getCount(), Toast.LENGTH_SHORT).show();
				}
				else{
					//データnullなのでなにもしない(今はテストでtoast)
					Toast.makeText(context, "結果カーソルはnull", Toast.LENGTH_SHORT).show();
				}
				c.close();
				conn.close();
				}catch(Exception e){
					Log.e("MMapView","DB select:"+e);
				}
			}
		});

		/*
		 * serviceからのintent受信
		 */
		// インテントからのパラメータ取得
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			mapUpdate(extras);
		}

	}

	@Override
	protected void onResume() {

		super.onResume();
	}

	@Override
	public void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		Bundle extras = intent.getExtras();
		if (extras != null) {
			mapUpdate(extras);
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private void mapUpdate(Bundle extras) {
		double lat, lng;
		lat = extras.getDouble("lat");
		lng = extras.getDouble("lng");

		// 地図の中心位置を移動する
		GeoPoint gp = new GeoPoint(
				(int) (lat*1E6),
				(int) (lng* 1E6));
		 mMapController.animateTo(gp);
		 // tFooter set
		 tv0.setText("経度=" + lng+",緯度=" + lat );
	}
}

MLocationManager.java

package com.efolab._service;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.efolab._db.DbConnection;
import com.efolab._util.MNotification;
import com.efolab._util.MUtil;
import com.efolab.t201.MMapView;
import com.efolab.t201.R;
import com.google.android.maps.GeoPoint;

public class MLocationManager extends Service {
	Context context;
	LocationManager mLocationManager;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		context = getApplicationContext();
		Log.v("MLocationManager","onStart");
		//Notification START
		MNotification mNotification = new MNotification(this.getClass());
		String ticker , title , message;
		ticker = this.getClass().getName();
		title = "ロケーションサービス("+startId+")";
		message =MUtil._Date.getStringDateTime()+"起動しています。";
		mNotification.show(context, R.drawable.ic_launcher, ticker, title, message);
		//Notification END
		
		mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				1000, 1, l);
		
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.v("MLocationManager","onDestroy");
		//Notification START
		MNotification mNotification = new MNotification(this.getClass());
		String ticker , title , message;
		ticker = this.getClass().getName();
		title = "ロケーションサービス";
		message =MUtil._Date.getStringDateTime()+"停止しています。";
		mNotification.show(context, R.drawable.ic_launcher, ticker, title, message);
		//Notification END
		
		//位置情報の更新を停止
		mLocationManager.removeUpdates(l);
	}
	LocationListener l = new LocationListener() {
		int counter = 1;
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onLocationChanged(Location location) {
			GeoPoint gp = new GeoPoint(
					(int) (location.getLatitude() * 1E6),
					(int) (location.getLongitude() * 1E6));
			// 緯度の取得
			double lat = gp.getLatitudeE6() / 1E6;
			// 経度の取得
			double lng = gp.getLongitudeE6() / 1E6;
			
			Log.v("MLocationManager","位置更新:lat="+lat+",lng="+lng);
			
			Intent newIntent = new Intent(context , MMapView.class);
			newIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			newIntent.setAction("LOCATION_UPDATE:"+(counter++));//値を変更してやること:受け取り側での引数の内容が更新されなくなる

			newIntent.putExtra("lat", lat);
			newIntent.putExtra("lng", lng);
			//getActivityでPendingIntentを生成
			PendingIntent pending = PendingIntent.getActivity(context, 0, newIntent, 0);
			try {
			     pending.send();
			} catch (CanceledException e) {
			     // TODO Auto-generated catch block
			     e.printStackTrace();
			}
			//DBへの書込み
			DbConnection connection = new DbConnection(context);
			String sql = "insert into "+ DbConnection.DBTABLE + " (lat ,lng ) values (" + lat +"," + lng +");";
			connection.openAndExec(sql);
			connection.close();
		}
	};


}

DbConnection.java

package com.efolab._db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbConnection {
	private SQLiteDatabase db = null;
	private static DbOpenHelper dbHelper = null;
	private Cursor cursor = null;
	private static final int DBVER = 3;
	public static final String DBNAME = "geo";
	public static final String DBTABLE = "t_latlng";
	// private static String CREATE_TABLE = "create table if not exists  "
	private static String CREATE_TABLE = "create table  " + DBTABLE + " ("
			+ "no INTEGER primary key autoincrement" + ",lat REAL not null "
			+ ",lng REAL not null" + ",send_flg integer DEFAULT 0"
			+ ",del_flg integer DEFAULT 0"
			+ ",update_date TIMESTAMP DEFAULT (DATETIME('now','localtime'))"
			+ ");";

	public DbConnection(Context context) {
		if (dbHelper == null) {
			dbHelper = new DbOpenHelper(context, DBNAME, null, DBVER);
			Log.v("DbConnection", "dbHelper = null");
		} else {
			Log.v("DbConnection", "deHelper != null");
		}
		//テーブルの存在確認
		if(isTableExists() == false){
			//テーブルがないときはCREATE_TABLEを投げる
			db.execSQL(CREATE_TABLE);
		}
	}

	// insert
	/**
	 * @return void
	 * @param String
	 */
	public void openAndExec(String sql) {
		db = dbHelper.getWritableDatabase();
		db.execSQL(sql);
		db.close();
	}

	// select
	/**
	 * 
	 * @param String
	 * @return Cursor
	 */
	public Cursor openAndSelect(String sql) {
		// FIXME : テーブル生成されていないときに実行するとエラー発生
		// selectを投げるまえにtableの存在確認
		//テーブルが存在するときにだけ、selectを投げる
		if (isTableExists()) {
			try {
				db = dbHelper.getReadableDatabase();
				cursor = db.rawQuery(sql, null);
			} catch (Exception e) {
				Log.e("DbConnection", "エラー:" + e);
				cursor = null;
			}

		} else {
			//テーブルが存在しないとき
			cursor = null;
		}
		return cursor;
	}

	// close
	/**
	 * カーソルとデータベース接続を閉じる
	 * 
	 * @param なし
	 * @return void
	 */
	public void close() {
		if (cursor != null) {
			cursor.close();
		}
		if (db != null) {
			db.close();
		}
	}

	private boolean isTableExists() {
		boolean ret = false;
		String kakunin_sql = "select count(*) from sqlite_master where type='table' and name= '"
				+ DbConnection.DBTABLE + "';";
		Log.v("DbConnection", "kakunin_sql=" + kakunin_sql);
		db = dbHelper.getReadableDatabase();
		Cursor c = db.rawQuery(kakunin_sql, null);
		c.moveToFirst();
		Log.v("DbConnection", "テーブル存在確認結果:" + c.getInt(0));
		if (c.getInt(0) == 1) {
			// テーブルが存在する
			ret = true;
		}
		c.close();
		return ret;
	}

	private static class DbOpenHelper extends SQLiteOpenHelper {

		public DbOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);

		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// GeoPoint用のテーブルを生成する
			db.execSQL(CREATE_TABLE);
			Log.v("DbConnection", "onCreate sql=" + CREATE_TABLE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// GeoPoint用のテーブルを生成する
			db.execSQL(CREATE_TABLE);
			Log.v("DbConnection", "onUpgrade sql=" + CREATE_TABLE);
		}
	}
}