android 定位

package com.ejoy.android.servicelist;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.ejoy.android.MainActivity;
import com.ejoy.dal.DALAreaHelper;
import com.ejoy.dal.DALLocationHelper;
import com.ejoy.json.HttpConstant;
import com.ejoy.model.UserLocation;
import com.ejoy.utils.StringUtils;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;

/**
 * Service会经历 onCreate --> onStart stopService的时候直接onDestroy
 * Service只会运行onCreate, 这个时候 调用者和Service绑定在一起
 * 调用者退出了,Srevice就会调用onUnbind-->onDestroyed
 */
public class LocationMapService extends Service {
	private OnGetLocalOkListener mLocalOkListener = null;
	private HttpClient httpclient;
	private HttpParams httpParameters;
	private int timeoutConnection = 3000;
	private int timeoutSocket = 5000;
	FileWriter mFileWriter = null;
	private CommandReceiver cmdReceiver;
	private MyBinder myBinder = new MyBinder();
	private DALLocationHelper dalLocationHelper = null;
	private DALAreaHelper mDalAreaHelper = null;

	// 设置监听类的引用对象
	public void setOnGetLocalOkListener(OnGetLocalOkListener listener) {
		mLocalOkListener = listener;
	}

	// 通过经纬度获取地理信息
	private void getLocalByItude(String latitude, String longitude) {
		HttpURLConnection conn = null;
		String line = null;
		try {
			URL url = new URL("http://maps.google.cn/maps/geo?key=abcdefg&q="
					+ latitude + "," + longitude);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(timeoutConnection);
			conn.setReadTimeout(timeoutSocket);
			conn.setRequestMethod("GET");
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufReader = new BufferedReader(inStreamReader);
			StringBuffer bufStr = new StringBuffer();

			while ((line = bufReader.readLine()) != null) {
				bufStr.append(line);
			}
			line = bufStr.toString();
			if (line != null && line.length() > 0) {
				JSONObject jsonobject = new JSONObject(line);
				JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark")
						.toString());
				line = "";
				String scity = "";
				String sstreet = "";
				String mCountry = "";
				String proviceString = "";
				for (int i = 0; i < jsonArray.length(); i++) {
					line = jsonArray.getJSONObject(i).getString("address");
					scity = jsonArray.getJSONObject(i).getString(
							"AddressDetails");
				}
				JSONObject jsonObject2 = new JSONObject(scity);
				JSONObject jsonObject3 = new JSONObject(jsonObject2.get(
						"Country").toString());
				JSONObject jsonObject4 = new JSONObject(jsonObject3.get(
						"AdministrativeArea").toString());
				proviceString = jsonObject4.getString("AdministrativeAreaName");
				JSONObject jsonObject8 = new JSONObject(jsonObject4.get(
						"Locality").toString());
				scity = jsonObject8.getString("LocalityName");
				JSONObject jsonObject5 = new JSONObject(jsonObject8.get(
						"DependentLocality").toString());
				mCountry = jsonObject5.getString("DependentLocalityName");// 县
				JSONObject jsonObject6 = new JSONObject(jsonObject5.get(
						"Thoroughfare").toString());
				// 城市
				sstreet = jsonObject6.getString("ThoroughfareName").toString();

				// 回调
				mLocalOkListener.onGetOk(latitude, longitude, line, scity,
						sstreet, mCountry, proviceString);
			}
		} catch (Exception e) {
			mLocalOkListener.onGetOk("", "", "", "", "", "", "");
		} finally {
			if (conn != null) {
				conn.disconnect();
				mLocalOkListener.onGetOk("", "", "", "", "", "", "");
			}
		}
	}

	// 获得主线程的Handler
	private Handler mHandler = new Handler(Looper.getMainLooper());

	public void getItude() {
		// 匿名内部类,回调调用的函数
		// 开启新的线程去获取经纬度
		new Thread(new Runnable() {
			public void run() {
				try {
					TelephonyManager mTelNet = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
					String operator = mTelNet.getNetworkOperator();
					String mcc = operator.substring(0, 3);
					String mnc = operator.substring(3);
					GsmCellLocation location = (GsmCellLocation) mTelNet
							.getCellLocation();

					int cid = location.getCid();
					int lac = location.getLac();
					httpParameters = new BasicHttpParams();
					HttpConnectionParams.setConnectionTimeout(httpParameters,
							timeoutConnection);
					HttpConnectionParams.setSoTimeout(httpParameters,
							timeoutSocket);
					httpclient = new DefaultHttpClient(httpParameters);
					HttpPost post = new HttpPost(
							"http://www.google.com/loc/json");
					try {
						JSONObject holder = new JSONObject();
						holder.put("version", "1.1.0");
						holder.put("host", "maps.google.com");
						holder.put("address_language", "zh_CN");
						holder.put("request_address", true);
						JSONObject tower = new JSONObject();
						tower.put("mobile_country_code", mcc);
						tower.put("mobile_network_code", mnc);
						tower.put("cell_id", cid);
						tower.put("location_area_code", lac);

						JSONArray towerarray = new JSONArray();
						towerarray.put(tower);

						holder.put("cell_towers", towerarray);

						StringEntity query = new StringEntity(holder.toString());
						post.setEntity(query);
						HttpResponse response = httpclient.execute(post);
						HttpEntity entity = response.getEntity();
						BufferedReader buffReader = new BufferedReader(
								new InputStreamReader(entity.getContent()));
						StringBuffer strBuff = new StringBuffer();
						String result = null;
						while ((result = buffReader.readLine()) != null) {
							strBuff.append(result);
						}
						JSONObject json = new JSONObject(strBuff.toString());
						JSONObject subjosn = new JSONObject(json
								.getString("location"));
						String strLatString = subjosn.getString("latitude");
						String strLngString = subjosn.getString("longitude");
						double ddouble = Double.valueOf(strLngString);
						double sdouble = Double.valueOf(strLatString);
						try {
							String str = "lat=" + subjosn.getString("latitude")
									+ "&lng=" + subjosn.getString("longitude");
							String StrjsonString = com.ejoy.json.HttpUtils
									.getDataString(HttpConstant.strWebGetSysLocationPathString
											+ "?" + str);
							JSONObject jsonObject = new JSONObject(
									StrjsonString);
							JSONObject josnJsonObject = new JSONObject(
									jsonObject.getString("ulocation"));
							String flag = josnJsonObject.getString("errorcode");
							switch (StringUtils.StringInt(flag)) {
							case 0:
								String string = josnJsonObject
										.getString("mctx");
								JSONObject sts = new JSONObject(string);
								JSONArray sArray = new JSONArray(sts
										.getString("ulocan"));
								for (int i = 0; i < sArray.length();) {
									JSONObject sJsonObject = sArray
											.getJSONObject(i);
									sdouble = Double.valueOf(strLatString)
											+ Double.valueOf(sJsonObject
													.getString("OffsetLat"));
									ddouble = Double.valueOf(strLngString)
											+ Double.valueOf(sJsonObject
													.getString("OffsetLng"));
									break;
								}
								break;
							}
						} catch (Exception e) {

						}
						getLocalByItude(StringUtils.DoubleString(sdouble),
								StringUtils.DoubleString(ddouble));
					} catch (org.apache.http.conn.ConnectTimeoutException e) {
					} catch (Exception e) {
						mLocalOkListener.onGetOk("", "", "", "", "", "", "");
					} finally {
						post.abort();
						httpclient = null;
					}
				} catch (Exception e) {
					mLocalOkListener.onGetOk("", "", "", "", "", "", "");
				}
			}
		}).start();

	}

	/**
	 * 保存到数据库
	 * 
	 * @param latitude
	 *            纬度
	 * @param longitude
	 *            经度
	 * @param local
	 *            长地址
	 * @param Intro
	 *            城市
	 * @param mCountry
	 *            县级
	 * @throws Exception
	 */
	public void SaveToDB(String latitude, String longitude, String local,
			String Intro, String Street, String mCountry, String provice) {
		try {
			UserLocation modelLocation = new UserLocation();
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy年MM月dd日   HH:mm:ss");
			Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
			modelLocation.setCreateDT(formatter.format(curDate));
			modelLocation.setLocationIntro(Intro);
			modelLocation.setLocationlatitude(latitude);
			modelLocation.setLocationlongitude(longitude);
			modelLocation.setLocationPath(local);
			modelLocation.setLocationStreet(Street);
			modelLocation.setLocationCountry(mCountry);
			Editor sharedata = getSharedPreferences("ejoylocaiotn", 0).edit();
			sharedata.putString("latitude", latitude);
			sharedata.putString("longitude", longitude);
			sharedata.putString("Intro", Intro);
			sharedata.putString("local", local);
			sharedata.putString("Street", Street);
			sharedata.putString("mCountry", mCountry);
			sharedata.putString("provice", provice);
			sharedata.putString("date", formatter.format(curDate));
			sharedata.commit();
			dalLocationHelper.AddLocation(modelLocation);
			try {
				// 更新地区信息
				// 获取县级ID
				int i = mDalAreaHelper.GetAreaCursorCityId(mCountry, 3);
				mDalAreaHelper.SaveStreetMsgByParentIDjson(i);
			} catch (Exception er) {
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return myBinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// 当调用者退出(即使没有调用unbindService)或者主动停止服务时会调用
		stopSelf();
		return super.onUnbind(intent);
	}

	@Override
	public void onCreate() {
		// StartService方法执行-->OnCreate()->OnStart()->
		// BindService方法执行-->OnCreate()->onDestroy
		// 重写onCreate方法

		dalLocationHelper = new DALLocationHelper(LocationMapService.this);
		mDalAreaHelper = new DALAreaHelper(LocationMapService.this);
		cmdReceiver = new CommandReceiver();
		IntentFilter filter = new IntentFilter();// 创建IntentFilter对象
		filter.addAction("com.ejoy.servicelist.LocationMapService");
		registerReceiver(cmdReceiver, filter);// 注册Broadcast Receiver
		// 回调函数的事件方法处理
		this.setOnGetLocalOkListener(new OnGetLocalOkListener() {
			public void onGetOk(String latitude, String longitude,
					String local, String Intro, String Street,
					String CountryString, String provice) {

				final String flatitude = latitude;
				final String flongitude = longitude;
				final String fIntro = Intro;
				final String mlocal = local;
				final String fStreet = Street;
				final String mCountry = CountryString;
				final String mproviceString = provice;
				mHandler.post(new Runnable() {
					public void run() {
						if (mlocal != null) {
							if (mlocal.length() > 0) {
								new Thread(new Runnable() {
									public void run() {
										SaveToDB(flatitude, flongitude, mlocal,
												fIntro, fStreet, mCountry,
												mproviceString);
										Intent intent = new Intent();// 创建Intent对象
										intent.setAction("com.ejoy.android.MainActivity");
										intent.putExtra("address", mlocal);
										intent.putExtra("city", fIntro);
										intent.putExtra("street", fStreet);
										sendBroadcast(intent);// 发送广播
									}
								}).start();
							} else {
							}
						}
					}
				});

			}
		});
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// 进行开始
		super.onStart(intent, startId);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		// 重写onDestroy方法
		if (cmdReceiver != null) {
			this.unregisterReceiver(cmdReceiver);// 取消注册的CommandReceiver
			cmdReceiver = null;
		}
		if (dalLocationHelper != null) {
			dalLocationHelper.CloseDb();
		}
		if (mDalAreaHelper != null) {
			mDalAreaHelper.CloseDb();
		}
		super.onDestroy();
	}

	public class MyBinder extends Binder {
		public LocationMapService getService() {
			return LocationMapService.this;
		}
	}

	private class CommandReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 重写onReceive方法
			int cmd = intent.getIntExtra("cmd", MainActivity.CMD_STOP_SERVICE);// 获取Extra信息
			if (cmd == MainActivity.CMD_STOP_SERVICE) {
				// 如果发来的消息是停止服务
				stopSelf();// 停止服务
			}
		}
	}

	// 监听类接口
	public interface OnGetLocalOkListener {
		/**
		 * @param latitude
		 *            纬度
		 * @param longitude
		 *            经度
		 * @param local
		 *            长地址
		 * @param Intro
		 *            城市
		 * @param Street
		 *            街道
		 * @param mCountry
		 *            县级
		 */
		void onGetOk(String latitude, String longitude, String local,
				String Intro, String Street, String mCountry, String provice);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值