GPS实时定位、获取基站信息

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/RuningLING/article/details/78057924

好久没有来更新我的博客了 , 最近刚做了一个GPS实时定位和获取基站信息的一个小的Demo ,这个辛酸泪啊~ 来给大家们来分享一下 !

做这个项目我用的是用的原始的手机GPS定位, 因为这个有可能需要在国外会用到,如果用国内第三方SDK的是用不了的,国外的第三方SDK的也需要翻墙什么的......不过用原始的还不错精确度还可以。


(网上的资料质量太水了)

下面给大家一些官方资料 :

基站相关资料

GPS资料


好啦不多说来看一下代码 :



package com.waywings.basestation.wy_terminal_basestation;

import android.annotation.TargetApi;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.CellIdentityCdma;
import android.telephony.CellIdentityGsm;
import android.telephony.CellIdentityLte;
import android.telephony.CellIdentityWcdma;
import android.telephony.CellInfo;
import android.telephony.CellInfoCdma;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.CellLocation;
import android.telephony.CellSignalStrengthCdma;
import android.telephony.CellSignalStrengthGsm;
import android.telephony.CellSignalStrengthLte;
import android.telephony.CellSignalStrengthWcdma;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.waywings.basestation.wy_terminal_basestation.bean.CellInfoCdmaBean;
import com.waywings.basestation.wy_terminal_basestation.bean.CellInfoGsmBean;
import com.waywings.basestation.wy_terminal_basestation.bean.CellInfoLteBean;
import com.waywings.basestation.wy_terminal_basestation.bean.CellInfoWcdmaBean;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class BaseStationActivity extends AppCompatActivity {

    private TextView tipInfo, basestation_info;
    private LocationManager locationManager;
    private static final String TAG = "BaseStationActivity";
    private final static int INTERVAL_REFRESH = 1000;
    private ArrayList<String> PROVIDER_ARRAY;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_station);
        initView();
        initLocationManager();
    }

    private void initLocationManager() {
        PROVIDER_ARRAY = new ArrayList<>();
        PROVIDER_ARRAY.add(LocationManager.GPS_PROVIDER);
        PROVIDER_ARRAY.add(LocationManager.NETWORK_PROVIDER);
        PROVIDER_ARRAY.add(LocationManager.PASSIVE_PROVIDER);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        List<String> allProviders = locationManager.getAllProviders();
        Log.i("AlexLocation", "AllProviders  -> " + allProviders);
        if (allProviders != null) {
            for (String provider : allProviders) {
                Log.i("AlexLocation", "AllProviders  ->  provider => " + provider);
                if ((provider != null) && (PROVIDER_ARRAY.contains(provider))) {
                    if (LocationManager.GPS_PROVIDER.equals(provider)) {
                        //通过GPS获取位置
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL_REFRESH, 10, locationListener);
                    } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
                        //通过网络获取位置
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, INTERVAL_REFRESH, 10, locationListener);
                    } else if (LocationManager.PASSIVE_PROVIDER.equals(provider)) {
                        //被动获取位置
                        locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, INTERVAL_REFRESH, 10, locationListener);
                    }
                }
            }
        }
    }

    private void initView() {
        tipInfo = (TextView) findViewById(R.id.tipInfo);
        basestation_info = (TextView) findViewById(R.id.basestation_info);
    }

    private LocationListener locationListener = new LocationListener() {
        //位置更改时调用
        @Override
        public void onLocationChanged(Location location) {
            if (location == null) return;
            showLocationInfo(location);
        }
        //当提供者状态更改时调用
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }
        //当提供程序由用户启用时调用
        @Override
        public void onProviderEnabled(String provider) {

        }
        //当用户禁用提供程序时调用
        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    /**
     * 显示当前设备的位置信息
     *
     * @param location
     */
    private void showLocationInfo(Location location) {
        // TODO Auto-generated method stub
        float accuracy = location.getAccuracy();//获取该位置的估计精度,以米为单位
        double altitude = location.getAltitude();//如果海拔高度在海拔高度,就可获得高度
        double longitude = location.getLongitude();//得到经度
        double latitude = location.getLatitude();//得到纬度
        float speed = location.getSpeed();//如果有可用的速度,以米/秒在地面上
        boolean b = location.hasAccuracy();//如果该位置具有精度,则为true

        String changeInfo = "\n时间:" + sdf.format(new Date())
                + "\n精度 : " + accuracy
                + "\n高度 : " + altitude
                + "\n经度 : " + longitude
                + "\n纬度 : " + latitude
                + "\n速度 : " + speed
                + "\n是否具有精度 : " + b;
        tipInfo.setText(changeInfo);


        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addressList = null;
        try {
            addressList = geocoder.getFromLocation(location.getAltitude(), location.getLongitude(), 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (addressList.size() <= 0 | addressList == null) return;
        Address address = addressList.get(0);
        //Log.i(TAG, "address =" + address);
        String countryName = address.getCountryName();//得到国家名称,比如:中国
        String locality = address.getLocality();//得到城市名称,比如:北京市
        Log.i(TAG, "\ncountryName = " + countryName + "\nlocality = " + locality);
        for (int i = 0; address.getAddressLine(i) != null; i++) {
            String addressLine = address.getAddressLine(i);//得到周边信息,包括街道等,i=0,得到街道名称
            Log.i(TAG, "addressLine = " + addressLine);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationManager != null) {
            // 关闭程序时将监听器移除
            locationManager.removeUpdates(locationListener);
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void baseStation(View view) {

        TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //返回设备的当前位置
        CellLocation cellLocation = mTelephonyManager.getCellLocation();
        List<CellInfo> CellInfo = mTelephonyManager.getAllCellInfo();
        StringBuffer stringBuffer = new StringBuffer("总数 : " + CellInfo.size() + "\n");

        CellInfoGsmBean gsmBean = new CellInfoGsmBean();
        CellInfoCdmaBean cdmaBean = new CellInfoCdmaBean();
        CellInfoLteBean lteBean = new CellInfoLteBean();
        CellInfoWcdmaBean wcdmaBean = new CellInfoWcdmaBean();
        basestation_info.setText("");
        if (cellLocation != null) {
            basestation_info.append(cellLocation.toString() + "\n");
        }

        for (CellInfo cellInfo : CellInfo) {
            stringBuffer.append(cellInfo.toString());
            //GSM手机信息
            if (cellInfo instanceof CellInfoGsm) {

                CellSignalStrengthGsm cellSignalStrength = ((CellInfoGsm) cellInfo).getCellSignalStrength();
                gsmBean.asuLevel = cellSignalStrength.getAsuLevel();
                gsmBean.dbm = cellSignalStrength.getDbm();
                gsmBean.level = cellSignalStrength.getLevel();


                CellInfoGsm cgsm = (CellInfoGsm) cellInfo;
                CellIdentityGsm cellIdentity = cgsm.getCellIdentity();
                gsmBean.cid = cellIdentity.getCid();
                gsmBean.lac = cellIdentity.getLac();
                gsmBean.mcc = cellIdentity.getMcc();
                gsmBean.mnc = cellIdentity.getMnc();

                basestation_info.append(gsmBean.toString() + "\n");
                Log.d(TAG, gsmBean.toString());
                //Log.d(TAG,"\nCID = " + cid + "\nLAC = " + lac + "\nMCC = " + mcc + "\nMNC = " + mnc);
            }
            //小区LTE
            if (cellInfo instanceof CellInfoLte) {
                CellSignalStrengthLte cellSignalStrength = ((CellInfoLte) cellInfo).getCellSignalStrength();
                lteBean.dbm = cellSignalStrength.getDbm();
                lteBean.asuLevel = cellSignalStrength.getAsuLevel();
                lteBean.timingAdvance = cellSignalStrength.getTimingAdvance();
                lteBean.level = cellSignalStrength.getLevel();

                CellIdentityLte cellIdentity = ((CellInfoLte) cellInfo).getCellIdentity();
                lteBean.mcc = cellIdentity.getMcc();
                lteBean.mnc = cellIdentity.getMnc();
                lteBean.ci = cellIdentity.getCi();
                lteBean.pci = cellIdentity.getPci();
                lteBean.tac = cellIdentity.getTac();

                basestation_info.append(lteBean.toString() + "\n");
                Log.d(TAG, lteBean.toString());
                Log.d(TAG, "\nmcc = " + lteBean.mcc + "\nmnc = " + lteBean.mnc + "\nci = " + lteBean.ci + "\npci = " + lteBean.pci);
            }
            //CDMA手机信息
            if (cellInfo instanceof CellInfoCdma) {
                CellSignalStrengthCdma cellSignalStrength = ((CellInfoCdma) cellInfo).getCellSignalStrength();
                cdmaBean.asuLevel = cellSignalStrength.getAsuLevel();
                cdmaBean.cdmaDbm = cellSignalStrength.getCdmaDbm();
                cdmaBean.cdmaEcio = cellSignalStrength.getCdmaEcio();
                cdmaBean.cdmaLevel = cellSignalStrength.getCdmaLevel();
                cdmaBean.dbm = cellSignalStrength.getDbm();
                cdmaBean.evdoDbm = cellSignalStrength.getEvdoDbm();
                cdmaBean.evdoEcio = cellSignalStrength.getEvdoEcio();
                cdmaBean.evdoLevel = cellSignalStrength.getEvdoLevel();
                cdmaBean.evdoSnr = cellSignalStrength.getEvdoSnr();
                cdmaBean.level = cellSignalStrength.getLevel();
                CellIdentityCdma cellIdentity = ((CellInfoCdma) cellInfo).getCellIdentity();
                cdmaBean.basestationId = cellIdentity.getBasestationId();
                cdmaBean.latitude = cellIdentity.getLatitude();
                cdmaBean.longitude = cellIdentity.getLongitude();
                cdmaBean.networkId = cellIdentity.getNetworkId();
                cdmaBean.systemId = cellIdentity.getSystemId();

                basestation_info.append(cdmaBean.toString() + "\n");
                Log.d(TAG, cdmaBean.toString());
            }
            //WCDMA手机信息
            if (cellInfo instanceof CellInfoWcdma) {
                CellSignalStrengthWcdma cellSignalStrength = ((CellInfoWcdma) cellInfo).getCellSignalStrength();
                wcdmaBean.asuLevel = cellSignalStrength.getAsuLevel();
                wcdmaBean.dbm = cellSignalStrength.getDbm();
                wcdmaBean.level = cellSignalStrength.getLevel();
                CellIdentityWcdma cellIdentity = ((CellInfoWcdma) cellInfo).getCellIdentity();
                wcdmaBean.cid = cellIdentity.getCid();
                wcdmaBean.lac = cellIdentity.getLac();
                wcdmaBean.mcc = cellIdentity.getMcc();
                wcdmaBean.psc = cellIdentity.getPsc();
                basestation_info.append(wcdmaBean.toString() + "\n");
                Log.d(TAG, wcdmaBean.toString());
            }
        }
        //Log.d(TAG,stringBuffer.toString());
    }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:background="#ccc"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="3">

        <TextView
            android:id="@+id/tipInfo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="正在获取..."
            />
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <Button
            android:onClick="baseStation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="获取基站信息"/>
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        <TextView
            android:id="@+id/basestation_info"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        </ScrollView>
    </LinearLayout>

</LinearLayout>

最后给 AndroidManifest 添加权限


<!-- 连接互联网Internet权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- GPS定位权限 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>


最后来看一下最终的效果图 :




如果是定位没有成功有可能是,手机GPS没有打开、在室内会很慢几乎获取不到(强烈建议室外获取)!


展开阅读全文

没有更多推荐了,返回首页