在Android裡完美實現基站和WIFI定位
關於定位原理網上很多,這裡就不多說了。下面說怎麼實現的,直接貼程式碼如下:
首先是Util類:
- 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.impl.client.DefaultHttpClient;
- import org.json.JSONArray;
- import org.json.JSONObject;
- import android.content.Context;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.util.Log;
- public class Util {
- //log的標籤
- public static final String TAG = "location";
- public static final boolean DEBUG = true;
- public static final String LOCATION_URL = "http://www.google.com/loc/json";
- public static final String LOCATION_HOST = "maps.google.com";
- public static void logi(String content){
- if(DEBUG) {
- Log.i(TAG, content);
- }
- }
- public static void loge(String content){
- if(DEBUG) {
- Log.e(TAG, content);
- }
- }
- public static void logd(String content){
- if(DEBUG) {
- Log.d(TAG, content);
- }
- }
- /**
- * 獲取地理位置
- *
- * @throws Exception
- */
- public static String getLocation(String latitude, String longitude) throws Exception {
- String resultString = "";
- /** 這裡採用get方法,直接將引數加到URL上 */
- String urlString = String.format("http://maps.google.cn/maps/geo?key=abcdefg&q=%s,%s", latitude, longitude);
- Util.logi("Util: getLocation: 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;
- }
- /**
- * 判斷網路是否可用
- * @param context
- * @return
- */
- public static boolean isNetworkAvaliable(Context context){
- ConnectivityManager manager = (ConnectivityManager) (context
- .getSystemService(Context.CONNECTIVITY_SERVICE));
- NetworkInfo networkinfo = manager.getActiveNetworkInfo();
- return !(networkinfo == null || !networkinfo.isAvailable());
- }
- /**
- * 判斷網路型別 wifi 3G
- *
- * @param context
- * @return
- */
- public static boolean isWifiNetwrokType(Context context) {
- ConnectivityManager connectivityManager = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo info = connectivityManager.getActiveNetworkInfo();
- if (info != null && info.isAvailable()) {
- if (info.getTypeName().equalsIgnoreCase("wifi")) {
- return true;
- }
- }
- return false;
- }
- }
在MainActivity中根據當前網路環境,決定用WIFI定位還是基站定位
- import com.demo.location.cell.CellLocationManager;
- import com.demo.location.wifi.WifiLocationManager;
- import android.app.Activity;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- private TextView mTextView;
- private Button mButton;
- private WifiLocationManager wifiLocation;
- private CellLocationManager cellLocation;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mTextView = (TextView) findViewById(R.id.tv_show_info);
- mButton = (Button) findViewById(R.id.btn_get_info);
- wifiLocation = new WifiLocationManager(MainActivity.this);
- cellLocation = new CellLocationManager(MainActivity.this);
- mButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Util.logi("MainActivity: on mButton Click!!!");
- getLocation();
- }
- });
- }
- private void getLocation(){
- boolean isNet = Util.isNetworkAvaliable(MainActivity.this);
- if(!isNet){
- Toast.makeText(MainActivity.this, "網路不可用:開啟WIFI 或 資料連線!!!", Toast.LENGTH_LONG).show();
- Util.logd("MainActivity: getLocation: Net work is not avaliable, and return!!!");
- return;
- }
- boolean isWifi = Util.isWifiNetwrokType(MainActivity.this);
- if(isWifi){
- Util.logd("MainActivity: getLocation: Wifi定位");
- wifiLocation.getLocation(new WifiReceiver());
- }else{
- Util.logd("MainActivity: getLocation: 基站定位");
- String location = cellLocation.getLocationCell();
- mTextView.setText(location);
- }
- }
- class WifiReceiver extends BroadcastReceiver {
- public void onReceive(Context c, Intent intent) {
- Util.logi("get broadcastReceiver: SCAN_RESULTS_AVAILABLE_ACTION");
- String location = wifiLocation.getLocationWifi();
- mTextView.setText(location);
- }
- }
- }
1. WIFI定位:
WIFI定位的實現在WifiLocationManager.java裡
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.List;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.ClientProtocolException;
- 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.json.JSONArray;
- import org.json.JSONObject;
- import com.demo.location.Util;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.IntentFilter;
- import android.net.wifi.ScanResult;
- import android.net.wifi.WifiManager;
- public class WifiLocationManager {
- private Context mContext;
- private WifiManager wifiManager;
- public WifiLocationManager(Context context){
- mContext = context;
- wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
- }
- public void getLocation(BroadcastReceiver receiver){
- mContext.registerReceiver(receiver, new IntentFilter(
- WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
- wifiManager.startScan();
- }
- public List<ScanResult> getWifiList(){
- return wifiManager.getScanResults();
- }
- public String getLocationWifi(){
- /** 採用Android預設的HttpClient */
- HttpClient client = new DefaultHttpClient();
- /** 採用POST方法 */
- HttpPost post = new HttpPost(Util.LOCATION_URL);
- try {
- /** 構造POST的JSON資料 */
- JSONObject holder = new JSONObject();
- holder.put("version", "1.1.0");
- holder.put("host", Util.LOCATION_HOST);
- holder.put("address_language", "zh_CN");
- holder.put("request_address", true);
- JSONArray towerarray = new JSONArray();
- List<ScanResult> wifiList = getWifiList();
- for (int i = 0; i < wifiList.size(); i++) {
- JSONObject tower = new JSONObject();
- tower.put("mac_address", wifiList.get(i).BSSID);
- tower.put("ssid", wifiList.get(i).SSID);
- tower.put("signal_strength", wifiList.get(i).level);
- towerarray.put(tower);
- }
- holder.put("wifi_towers", towerarray);
- Util.logd("holder.put: " + holder.toString());
- 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);
- }
- Util.logd("result: " + strBuff.toString());
- /** 解析返回的JSON資料獲得經緯度 */
- JSONObject json = new JSONObject(strBuff.toString());
- JSONObject subjosn = new JSONObject(json.getString("location"));
- String latitude = subjosn.getString("latitude");
- String longitude = subjosn.getString("longitude");
- return Util.getLocation(latitude, longitude);
- } catch(ClientProtocolException e){
- Util.loge("ClientProtocolException : " + e.getMessage());
- }catch(IOException e){
- Util.loge("IOException : " + e.getMessage());
- } catch (Exception e) {
- Util.loge("Exception : " + e.getMessage());
- } finally{
- post.abort();
- client = null;
- }
- return null;
- }
- }
2.基站定位
基站定位的實現在CellLocationManager.java中
- 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.HttpPost;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.json.JSONArray;
- import org.json.JSONObject;
- import com.demo.location.Util;
- import android.content.Context;
- import android.telephony.TelephonyManager;
- import android.telephony.gsm.GsmCellLocation;
- public class CellLocationManager {
- private Context mContext;
- public CellLocationManager(Context context){
- mContext = context;
- }
- /** 基站資訊結構體 */
- public class SCell{
- public int MCC;
- public int MNC;
- public int LAC;
- public int CID;
- }
- /**
- * 獲取基站資訊
- *
- * @throws Exception
- */
- private SCell getCellInfo() throws Exception {
- SCell cell = new SCell();
- /** 呼叫API獲取基站資訊 */
- TelephonyManager mTelNet = (TelephonyManager) mContext.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;
- }
- public String getLocationCell(){
- SCell cell = null;
- try {
- cell = getCellInfo();
- } catch (Exception e1) {
- Util.loge("getLocationCell: getCellInfo: error: " + e1.getMessage());
- return null;
- }
- /** 採用Android預設的HttpClient */
- HttpClient client = new DefaultHttpClient();
- /** 採用POST方法 */
- HttpPost post = new HttpPost(Util.LOCATION_URL);
- try {
- /** 構造POST的JSON資料 */
- JSONObject holder = new JSONObject();
- holder.put("version", "1.1.0");
- holder.put("host", Util.LOCATION_HOST);
- 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);
- // Util.logi("getLocationCell: mobile_country_code = " + cell.MCC );
- tower.put("mobile_network_code", cell.MNC);
- // Util.logi("getLocationCell: mobile_network_code = " + cell.MNC );
- tower.put("cell_id", cell.CID);
- // Util.logi("getLocationCell: cell_id = " + cell.CID );
- tower.put("location_area_code", cell.LAC);
- // Util.logi("getLocationCell: location_area_code = " + cell.LAC );
- JSONArray towerarray = new JSONArray();
- towerarray.put(tower);
- holder.put("cell_towers", towerarray);
- StringEntity query = new StringEntity(holder.toString());
- Util.logi("getLocationCell: holder: " + 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"));
- String latitude = subjosn.getString("latitude");
- String longitude = subjosn.getString("longitude");
- return Util.getLocation(latitude, longitude);
- } catch (Exception e) {
- Util.loge("getLocationCell: error: " + e.getMessage());
- } finally{
- post.abort();
- client = null;
- }
- return null;
- }
- }
下載原始碼請到:http://download.csdn.net/detail/liu_zhen_wei/4768794
相關文章
- LBS基站定位和GPS衛星定位對比
- 劫持GPS定位&劫持WIFI定位WiFi
- 基站定位與Wi-Fi定位?看這篇就夠了
- Android實現Rxjava2+Retrofit完美封裝AndroidRxJava封裝
- android ---------高德地圖實現定位和3D地圖顯示Android地圖3D
- 設計模式在Python中的完美實現設計模式Python
- Android開發之高德地圖實現定位Android地圖
- 利用HTML5定位功能,實現在百度地圖上定位HTML地圖
- 在 OpenResty 裡實現程式間通訊REST
- 高德在提升定位精度方面的探索和實踐
- GPS、基站、IP定位的區別及其應用方向
- 利用HTML5定位功能,實現在百度地圖上定位薦HTML地圖
- 在C#裡實現DATAGRID的列印預覽和列印 (轉)C#
- 如何在word裡實現在方框中打勾
- 機器學習在滴滴網路定位中的探索和實踐機器學習
- 用JavaScript和CSS3在HTML裡實現音樂視覺化效果JavaScriptCSSS3HTML視覺化
- [譯] Story 中 Type Mode 在 iOS 和 Android 上的實現iOSAndroid
- 在android的spinner中,實現取VALUE值和TEXT值。Android
- android wifiAndroidWiFi
- Android 完美實現手機號344格式化效果Android
- 華為釋出業界首款5G基站核心晶片:天罡晶片,實現基站尺寸縮小超50%!晶片
- 詳解在Android中整合高德定位功能Android
- efcore分表下"完美"實現
- bootstrap完美實現5列布局boot
- 高德地圖定位實現地圖
- Selenium實現元素定位
- android TextView裡邊實現圖文混配效果AndroidTextView
- 基於嵌入式板卡實現的藍芽AOA基站藍芽
- Vue完美記住滾動條和實現下拉載入Vue
- 什麼是共享WiFi專案,共享WiFi現在還可以做嗎?WiFi
- WIFI6比WIFI5好在哪裡呢?WiFi
- Android系統中通過shell命令實現wifi的連線控制AndroidWiFi
- 如何定位SQL語句在共享池裡用到了哪些chunksSQL
- 在ASP.NET裡輕鬆實現縮圖 (轉)ASP.NET
- Android TextView 在指定位置自動省略字元AndroidTextView字元
- AI 和 DevOps:實現高效軟體交付的完美組合AIdev
- Blazor Server完美實現Cookie Authorization and AuthenticationBlazorServerCookie
- 在程式碼中實現android:tint效果Android