代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
Java
】
android 定位
作者:
fuweiping
/ 发布于
2012/11/27
/
882
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); } }
试试其它关键字
定位
同语言下
.
List 切割成几份 工具类
.
一行一行读取txt的内容
.
Java PDF转换成图片并输出给前台展示
.
java 多线程框架
.
double类型如果小数点后为零则显示整数否则保留两位小
.
将图片转换为Base64字符串公共类抽取
.
sqlParser 处理SQL(增删改查) 替换schema 用于多租户
.
JAVA 月份中的第几周处理 1-7属于第一周 依次类推 29-
.
java计算两个经纬度之间的距离
.
输入时间参数计算年龄
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
fuweiping
贡献的其它代码
(
9
)
.
android 定位
.
安卓做旋转动画
.
android Listview下拉刷新
.
仿iphone的左右开关
.
异步的图片加载
.
Android 验证手机号码
.
仿快拍二维码的手动输码页面
.
从电脑版页面获取新闻正文html代码
.
android app首次进入的时候进行提醒操作
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3