基站定位程式

來源:互聯網
上載者:User


程式的作用是通過WIFI定位你當前所在位置。

主要參考的文章是:http://www.cnblogs.com/rayee/archive/2012/02/02/2336101.html

寫得十分清晰,最終效果也比android develop上的要好。

但代碼還是有一些小問題,原程式在點擊按鈕之後ProgressDialog無法顯示,增加一個

還加了一個TextView來顯示經緯度。


貼代碼

LauncherActivity.java

package com.android.demo;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.content.Intent;import android.os.Bundle;public class LauncherActivity extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.launcher);Timer timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubIntent goIntent = new Intent();goIntent.setClass(LauncherActivity.this, DemoActivity.class);startActivity(goIntent);}}, 3*1000);}}

DemoActivity.java

package com.android.demo;import java.io.BufferedReader;import java.io.InputStreamReader;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONArray;import org.json.JSONObject;import android.app.Activity;import android.app.ProgressDialog;import android.content.Context;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.telephony.TelephonyManager;import android.telephony.gsm.GsmCellLocation;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;import android.view.View.OnClickListener;public class DemoActivity extends Activity {private MyHandler myHandler;private SCell cell;private ProgressDialog mProgressDialog;/** 根據基站資料擷取經緯度 */private SItude itude;/** 擷取地理位置 */private String location;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);/** 為按鈕綁定事件 */Button btnGetLocation = (Button) findViewById(R.id.button1);btnGetLocation.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubonBtnClick();}});}/** 基站資訊結構體 */public class SCell{public int MCC;public int MNC;public int LAC;public int CID;}/** 經緯度資訊結構體 */public class SItude{public String latitude;public String longitude;}/** 按鈕點擊回呼函數 */private void onBtnClick() {/** 彈出一個等待狀態的框 */myHandler=new MyHandler();Toast.makeText(getApplicationContext(), "Ha", Toast.LENGTH_SHORT).show();mProgressDialog = new ProgressDialog(this);mProgressDialog.setMessage("正在擷取中...");mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);mProgressDialog.show();MyThread m = new MyThread();  new Thread(m).start();}/** * 擷取基站資訊 *  * @throws Exception */private SCell getCellInfo() throws Exception {SCell cell = new SCell();/** 調用API擷取基站資訊 */TelephonyManager mTelNet = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);GsmCellLocation location = (GsmCellLocation) mTelNet.getCellLocation();if (location == null)throw new Exception("擷取基站資訊失敗");String operator = mTelNet.getNetworkOperator();int mcc = Integer.parseInt(operator.substring(0, 3));int mnc = Integer.parseInt(operator.substring(3));int cid = location.getCid();int lac = location.getLac();/** 將獲得的資料放到結構體中 */cell.MCC = mcc;cell.MNC = mnc;cell.LAC = lac;cell.CID = cid;return cell;}/** * 擷取經緯度 *  * @throws Exception */private SItude getItude(SCell cell) throws Exception {SItude itude = new SItude();/** 採用Android預設的HttpClient */HttpClient client = new DefaultHttpClient();/** 採用POST方法 */HttpPost post = new HttpPost("http://www.google.com/loc/json");try {/** 構造POST的JSON資料 */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);holder.put("radio_type", "gsm");holder.put("carrier", "HTC");JSONObject tower = new JSONObject();tower.put("mobile_country_code", cell.MCC);tower.put("mobile_network_code", cell.MNC);tower.put("cell_id", cell.CID);tower.put("location_area_code", cell.LAC);JSONArray towerarray = new JSONArray();towerarray.put(tower);holder.put("cell_towers", towerarray);StringEntity query = new StringEntity(holder.toString());post.setEntity(query);/** 發出POST資料並擷取返回資料 */HttpResponse response = client.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);}/** 解析返回的JSON資料獲得經緯度 */JSONObject json = new JSONObject(strBuff.toString());JSONObject subjosn = new JSONObject(json.getString("location"));itude.latitude = subjosn.getString("latitude");itude.longitude = subjosn.getString("longitude");Log.i("Itude", itude.latitude + itude.longitude);} catch (Exception e) {Log.e(e.getMessage(), e.toString());throw new Exception("擷取經緯度出現錯誤:"+e.getMessage());} finally{post.abort();client = null;}return itude;}/** * 擷取地理位置 *  * @throws Exception */private String getLocation(SItude itude) throws Exception {String resultString = "";/** 這裡採用get方法,直接將參數加到URL上 */String urlString = String.format("http://maps.google.cn/maps/geo?key=abcdefg&q=%s,%s", itude.latitude, itude.longitude);Log.i("URL", urlString);/** 建立HttpClient */HttpClient client = new DefaultHttpClient();/** 採用GET方法 */HttpGet get = new HttpGet(urlString);try {/** 發起GET請求並獲得返回資料 */HttpResponse response = client.execute(get);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);}resultString = strBuff.toString();/** 解析JSON資料,獲得物理地址 */if (resultString != null && resultString.length() > 0) {JSONObject jsonobject = new JSONObject(resultString);JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark").toString());resultString = "";for (int i = 0; i < jsonArray.length(); i++) {resultString = jsonArray.getJSONObject(i).getString("address");}}} catch (Exception e) {throw new Exception("擷取物理位置出現錯誤:" + e.getMessage());} finally {get.abort();client = null;}return resultString;}/** 顯示結果 */private void showResult(SCell cell, String location,SItude itude) {TextView cellText = (TextView) findViewById(R.id.cellText);cellText.setText(String.format("基站資訊:mcc:%d, mnc:%d, lac:%d, cid:%d",cell.MCC, cell.MNC, cell.LAC, cell.CID));TextView locationText = (TextView) findViewById(R.id.lacationText);locationText.setText("物理位置:" + location);TextView itudeText=(TextView)findViewById(R.id.itudeText); itudeText.setText("經度:"+itude.latitude+"  緯度:"+itude.longitude);}class MyHandler extends Handler {  public MyHandler() {  }  public MyHandler(Looper L) {  super(L);  }  // 子類必須重寫此方法,接管資料  @Override  public void handleMessage(Message msg) {  // TODO Auto-generated method stub  Log.d("MyHandler", "handleMessage......");/** 顯示結果 */mProgressDialog.dismiss();if(msg.arg1==1){showResult(cell, location,itude);}super.handleMessage(msg);  // 此處可以更新UI  }  }  class MyThread implements Runnable {  public void run() { Message msg = new Message();  msg.arg1=1;try {  /** 擷取基站資料 */cell = getCellInfo();/** 根據基站資料擷取經緯度 */itude = getItude(cell);/** 擷取地理位置 */location = getLocation(itude);/** 關閉對話方塊 */  msg.arg1=1;myHandler.sendMessage(msg); // 向Handler發送訊息,更新UI } catch (InterruptedException e) {  // TODO Auto-generated catch block  /** 顯示錯誤 */TextView cellText = (TextView) findViewById(R.id.cellText);cellText.setText(e.getMessage());Log.e("Error", e.getMessage()); } catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}Log.d("thread.......", "mThread........");   }  }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.