Android基站定位——通过手机信号获取基站信息

转载请标明出处:http://blog.csdn.net/android_ls/article/details/8672442

基站定位原理:通过手机信号获取基站信息,然后调用第三方公开的根据基站信息查找基站的经纬度值,想要具体地址信息的再根据经纬度值获取具体的地址信息

一、通过手机信号获取基站信息

 通过TelephonyManager 获取lac:mcc:mnc:cell-id(基站信息)的解释:
 MCC,Mobile Country Code,移动国家代码(中国的为460);
 MNC,Mobile Network Code,移动网络号码(中国移动为0,中国联通为1,中国电信为2); 
 LAC,Location Area Code,位置区域码;
 CID,Cell Identity,基站编号;
 BSSS,Base station signal strength,基站信号强度。

具体实现代码如下:

package com.easipass.test;
 
import java.util.List;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
 
/**
 * 功能描述:通过手机信号获取基站信息
 * # 通过TelephonyManager 获取lac:mcc:mnc:cell-id
 * # MCC,Mobile Country Code,移动国家代码(中国的为460);
 * # MNC,Mobile Network Code,移动网络号码(中国移动为0,中国联通为1,中国电信为2); 
 * # LAC,Location Area Code,位置区域码;
 * # CID,Cell Identity,基站编号;
 * # BSSS,Base station signal strength,基站信号强度。
 * @author android_ls
 */
public class GSMCellLocationActivity extends Activity {
 
    private static final String TAG = "GSMCellLocationActivity";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        // 获取基站信息
        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
 
                TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
 
                // 返回值MCC + MNC
                String operator = mTelephonyManager.getNetworkOperator();
                int mcc = Integer.parseInt(operator.substring(0, 3));
                int mnc = Integer.parseInt(operator.substring(3));
 
                // 中国移动和中国联通获取LAC、CID的方式
                GsmCellLocation location = (GsmCellLocation) mTelephonyManager.getCellLocation();
                int lac = location.getLac();
                int cellId = location.getCid();
 
                Log.i(TAG, " MCC = " + mcc + "\t MNC = " + mnc + "\t LAC = " + lac + "\t CID = " + cellId);
 
                // 中国电信获取LAC、CID的方式
                /*CdmaCellLocation location1 = (CdmaCellLocation) mTelephonyManager.getCellLocation();
                lac = location1.getNetworkId();
                cellId = location1.getBaseStationId();
                cellId /= 16;*/
                
                // 获取邻区基站信息
                List<NeighboringCellInfo> infos = mTelephonyManager.getNeighboringCellInfo();
                StringBuffer sb = new StringBuffer("总数 : " + infos.size() + "\n");
                for (NeighboringCellInfo info1 : infos) { // 根据邻区总数进行循环
                    sb.append(" LAC : " + info1.getLac()); // 取出当前邻区的LAC
                    sb.append(" CID : " + info1.getCid()); // 取出当前邻区的CID
                    sb.append(" BSSS : " + (-113 + 2 * info1.getRssi()) + "\n"); // 获取邻区基站信号强度
                }
 
                Log.i(TAG, " 获取邻区基站信息:" + sb.toString());
 
            }
        });
 
    }
 
}

在AndroidManifest.xml添加获取位置信息的权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

点击“获取基站信息”的按钮后,Logcat的日志输出如下:

1、中国联通:


2、中国移动:

二、调用第三方公开的API(根据基站信息查找基站的经纬度值及地址信息)

      1、组拼JSON形式的请求参数

 /**
     * 获取JSON形式的基站信息
     * @param mcc 移动国家代码(中国的为460)
     * @param mnc 移动网络号码(中国移动为0,中国联通为1,中国电信为2); 
     * @param lac 位置区域码
     * @param cid 基站编号
     * @return json
     * @throws JSONException
     */
    private String getJsonCellPos(int mcc, int mnc, int lac, int cid) throws JSONException {
        JSONObject jsonCellPos = new JSONObject();
        jsonCellPos.put("version", "1.1.0");
        jsonCellPos.put("host", "maps.google.com");
 
        JSONArray array = new JSONArray();
        JSONObject json1 = new JSONObject();
        json1.put("location_area_code", "" + lac + "");
        json1.put("mobile_country_code", "" + mcc + "");
        json1.put("mobile_network_code", "" + mnc + "");
        json1.put("age", 0);
        json1.put("cell_id", "" + cid + "");
        array.put(json1);
 
        jsonCellPos.put("cell_towers", array);
        return jsonCellPos.toString();
    }

      2、通过HTTP协议网络请求源码: 

request URL:http://www.minigps.net/minigps/map/google/location
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:GBK,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:zh-CN,zh;q=0.8
Connection:keep-alive
Content-Length:191
Content-Type:application/json; charset=UTF-8
Cookie:bdshare_firstime=1356366713546; JSESSIONID=68243935CD3355089CF07A3A22AAB372
Host:www.minigps.net
Origin:http://www.minigps.net
Referer:http://www.minigps.net/map.html
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4
X-Requested-With:XMLHttpRequest
Request Payload
{"cell_towers":[{"mobile_network_code":"1","location_area_code":"43018","cell_id":"11152773","age":0,"mobile_country_code":"460"}],"host":"maps.google.com","version":"1.1.0"}
 
Response Headersview source
Content-Type:application/json
Date:Sat, 03 Jan 2013 14:03:15 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked

      

        3、用JAVA代码具体实现:

 /**
     * 调用第三方公开的API根据基站信息查找基站的经纬度值及地址信息
     */
    public String httpPost(String url, String jsonCellPos) throws IOException{
        byte[] data = jsonCellPos.toString().getBytes();
        URL realUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection();
        httpURLConnection.setConnectTimeout(6 * 1000);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
        httpURLConnection.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
        httpURLConnection.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
        httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
        httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
 
        httpURLConnection.setRequestProperty("Host", "www.minigps.net");
        httpURLConnection.setRequestProperty("Referer", "http://www.minigps.net/map.html");
        httpURLConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4X-Requested-With:XMLHttpRequest");
 
        httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        httpURLConnection.setRequestProperty("Host", "www.minigps.net");
 
        DataOutputStream outStream = new DataOutputStream(httpURLConnection.getOutputStream());
        outStream.write(data);
        outStream.flush();
        outStream.close();
 
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = httpURLConnection.getInputStream();
            return new String(read(inputStream));
        }
        return null;
    }

      4、读取返回的JSON数据流代码:

 /**
     * 读取IO流并以byte[]形式存储
     * @param inputSream InputStream
     * @return byte[]
     * @throws IOException
     */
    public byte[] read(InputStream inputSream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[1024];
        while ((len = inputSream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inputSream.close();
 
        return outStream.toByteArray();
    }

 

三、请求参数及返回结果的JSON形式:

      1、请求的JSON参数值:

       {
         "cell_towers":
            [
             {
                 "mobile_network_code":"1",
                 "location_area_code":"43018",
                 "cell_id":"11152773",
                 "age":0,
                 "mobile_country_code":"460"
             }
            ],
            "host":"maps.google.com",
            "version":"1.1.0"
        }

       2、返回的JSON结果值:

    {
     "location":
         {
             "latitude":"31.211389541625977",
             "longitude":"121.60332489013672",
             "address":
                 {"city":
                     "上海市浦东新区居里路432号;浦东新区光启安老院、第一三共制药上海公司、SUNPLUS[附近]",
                     "country":"",
                     "country_code":"",
                     "county":"",
                     "postal_code":"",
                     "region":"",
                     "street":"",
                     "street_number":""
                 }
         },
         "access_token":"dummytoken"
    }

四、完整代码及所需权限:

Java代码:

package com.easipass.test;
 
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
 
/**
 * 功能描述:单基站定位
 * @author android_ls
 */
public class GSMCellLocationActivity extends Activity {
 
    private static final String TAG = "GSMCellLocationActivity";
 
    private int mcc;
 
    private int mnc;
 
    private int lac;
 
    private int cid;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        // 获取基站信息
        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
 
                TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
 
                // 返回值MCC + MNC
                String operator = mTelephonyManager.getNetworkOperator();
                mcc = Integer.parseInt(operator.substring(0, 3));
                mnc = Integer.parseInt(operator.substring(3));
 
                // 中国移动和中国联通获取LAC、CID的方式
                GsmCellLocation location = (GsmCellLocation) mTelephonyManager.getCellLocation();
                lac = location.getLac();
                cid = location.getCid();
 
                Log.i(TAG, "MCC = " + mcc + "\t MNC = " + mnc + "\t LAC = " + lac + "\t CID = " + cid);
 
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            String json = getJsonCellPos(mcc, mnc, lac, cid);
                            Log.i(TAG, "request = " + json);
 
                            String url = "http://www.minigps.net/minigps/map/google/location";
                            String result = httpPost(url, json);
                            Log.i(TAG, "result = " + result);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }.start();
 
            }
        });
    }
 
    /**
     * 调用第三方公开的API根据基站信息查找基站的经纬度值及地址信息
     */
    public String httpPost(String url, String jsonCellPos) throws IOException{
        byte[] data = jsonCellPos.toString().getBytes();
        URL realUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection();
        httpURLConnection.setConnectTimeout(6 * 1000);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
        httpURLConnection.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
        httpURLConnection.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
        httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
        httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
 
        httpURLConnection.setRequestProperty("Host", "www.minigps.net");
        httpURLConnection.setRequestProperty("Referer", "http://www.minigps.net/map.html");
        httpURLConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4X-Requested-With:XMLHttpRequest");
 
        httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        httpURLConnection.setRequestProperty("Host", "www.minigps.net");
 
        DataOutputStream outStream = new DataOutputStream(httpURLConnection.getOutputStream());
        outStream.write(data);
        outStream.flush();
        outStream.close();
 
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = httpURLConnection.getInputStream();
            return new String(read(inputStream));
        }
        return null;
    }
 
    /**
     * 获取JSON形式的基站信息
     * @param mcc 移动国家代码(中国的为460)
     * @param mnc 移动网络号码(中国移动为0,中国联通为1,中国电信为2); 
     * @param lac 位置区域码
     * @param cid 基站编号
     * @return json
     * @throws JSONException
     */
    private String getJsonCellPos(int mcc, int mnc, int lac, int cid) throws JSONException {
        JSONObject jsonCellPos = new JSONObject();
        jsonCellPos.put("version", "1.1.0");
        jsonCellPos.put("host", "maps.google.com");
 
        JSONArray array = new JSONArray();
        JSONObject json1 = new JSONObject();
        json1.put("location_area_code", "" + lac + "");
        json1.put("mobile_country_code", "" + mcc + "");
        json1.put("mobile_network_code", "" + mnc + "");
        json1.put("age", 0);
        json1.put("cell_id", "" + cid + "");
        array.put(json1);
 
        jsonCellPos.put("cell_towers", array);
        return jsonCellPos.toString();
    }
 
    /**
     * 读取IO流并以byte[]形式存储
     * @param inputSream InputStream
     * @return byte[]
     * @throws IOException
     */
    public byte[] read(InputStream inputSream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[1024];
        while ((len = inputSream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inputSream.close();
 
        return outStream.toByteArray();
    }
 
}

在AndroidManifest.xml添加获取位置信息的权限:

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

五、测试网址:http://www.minigps.net/map.html

六、Google的基站定位http://www.google.com/loc/json或者http://www.google.com.hk/loc/json已不可用,访问返回404。官方给出的答复:https://developers.google.com/gears/?hl=zh-TW

 参考过的博客:echo3博主的json基站定位接口 免费使用

 

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
我了解你的要求,下面是获取手机基站信息的最新代码: ``` TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // 如果没有获得权限,则请求权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); return; } // 获取基站信息 CellLocation cellLocation = telephonyManager.getCellLocation(); if (cellLocation instanceof GsmCellLocation) { GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation; int cid = gsmCellLocation.getCid(); int lac = gsmCellLocation.getLac(); int mcc = Integer.parseInt(telephonyManager.getNetworkOperator().substring(0, 3)); int mnc = Integer.parseInt(telephonyManager.getNetworkOperator().substring(3)); // 打印基站信息 Log.d(TAG, "CID: " + cid); Log.d(TAG, "LAC: " + lac); Log.d(TAG, "MCC: " + mcc); Log.d(TAG, "MNC: " + mnc); } else if (cellLocation instanceof CdmaCellLocation) { // CDMA 网络,暂不处理 } else { // 无法获取基站信息 Log.d(TAG, "无法获取基站信息"); } ``` 这段代码可以通过调用 TelephonyManager 类中的getCellLocation() 方法来获取手机的基站信息,如果是 GSM 网络,则强转为 GsmCellLocation 类,获取基站 ID(cid),位置区域码(lac)、移动国家代码(mcc)和移动网络代码(mnc)等信息,并打印出来。需要注意的是,该方法需要获取 ACCESS_COARSE_LOCATION 权限才能使用,因此在调用之前需要先检查是否已经获取了该权限。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值