可运行的GPS获取经纬度和获取基站例子(环境Android Studio 3.5.2扒拉能运行的例子找到太辛苦了要么版本太老。)

可运行的GPS获取经纬度和获取基站例子(环境Android Studio 3.5.2扒拉能运行的例子找到太辛苦了要么版本太老。)

为了检测GPS和基站修改结果,结合网络例子。单独抠出来可运行实例,GPS原生启动慢要有心理准备。

直接上干货,(为了发布例子 有特意学了怎么申请权限)如果想省事就直接下载例子运行即可。

https://download.csdn.net/download/u012571756/13133465

package com.example.mylbs;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.LocationListener;
import android.location.LocationManager;

import static android.location.LocationManager.GPS_PROVIDER;
import static android.location.LocationManager.NETWORK_PROVIDER;

import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.CellIdentityGsm;
import android.telephony.CellIdentityLte;
import android.telephony.CellIdentityWcdma;
import android.telephony.CellInfo;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
View viewp;
//final Record record = recordList.get(curIndex);

private final int REQUEST_CODE_ADDRESS = 100;

EditText peditText, setmessage;

private Date date = null;
private Date ldate = null;
private TextView mtv;
private TelephonyManager tel;
private int gb = 0;
private LocationManager locationManager = null;
private int mMcc;
// 2 or 3-digit Mobile Network Code, 0..999
private int mMnc;
// 28-bit cell identity
private int mCi;
// physical cell id 0..503
private int mPci;
// 16-bit tracking area code
private int mTac;
// 18-bit Absolute RF Channel Number
private int mEarfcn;
AlertDialog.Builder alertDialog;
private static final int NOT_NOTICE = 2;//如果勾选了不再询问

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tel = (TelephonyManager) getSystemService(this.TELEPHONY_SERVICE);
    //setContentView(R.layout.layout);
    setContentView(R.layout.activity_main);
    mtv = findViewById(R.id.tv);
    mtv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "实现点击TextView事件", Toast.LENGTH_SHORT).show();
            editCell();
        }
    });
    /*

    btnServiceStart = findViewById(R.id.main_btnServiceStart);
    btnServiceStop = findViewById(R.id.main_btnServiceStop);
    btnServiceStatus = findViewById(R.id.main_btnServiceStatus);
    btnServiceStart.setOnClickListener(this);
    btnServiceStop.setOnClickListener(this);
    btnServiceStatus.setOnClickListener(this);
    */
    date = new Date();
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//保持竖屏
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//禁止熄屏

    locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
    //requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

    // alertDialog.setCancelable(false);

    //alertDialog.setFinishOnTouchOutside(false );
    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    Activity#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for Activity#requestPermissions for more details.
        requestRxPermissions(Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION);

    }else{
        editCell();
    }

}

@Override
protected void onDestroy() {
    gb = 1;
    locationManager.removeUpdates(mLocationListener01);
    locationManager.removeUpdates(mLocationListener02);
    super.onDestroy();
}

private Location updateToNewLocation(Location location) {
    System.out.println("--------zhixing--2--------");
    String latLongString;
    double lat = 0;
    double lng = 0;
    if (location != null) {

        lat = location.getLatitude();
        lng = location.getLongitude();

        int cid;
        int lac;
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            // return null;
            requestRxPermissions(Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION);
            return null;
        }

        TelephonyManager tm = (TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);
        List<CellInfo> cellInfos = tm.getAllCellInfo();
        //String additional_info = getCellInfo(cellInfos.get(0));
        if (cellInfos.get(0) instanceof CellInfoLte) {
            CellInfoLte cellInfoLte = (CellInfoLte) cellInfos.get(0);
            //cellInfoLte.getCellIdentity()
            CellIdentityLte cellIdentityLte = cellInfoLte.getCellIdentity();
            if (ldate == null) ldate = new Date();

            // mMcc=2147483647 mMnc=2147483647 mCi=2147483647 mPci=159 mTac=2147483647 mEarfcn=2452
            mtv.setText("");
            mtv.append("  启动时间:" + date + "\n");
            mMcc = cellIdentityLte.getMcc();
            mMnc = cellIdentityLte.getMnc();
            mCi = cellIdentityLte.getCi();
            mPci = cellIdentityLte.getPci();
            mTac = cellIdentityLte.getTac();
            mEarfcn = cellIdentityLte.getEarfcn();
            peditText.setText(mMcc + "," + mMnc + "," + mCi + "," + mPci + "," + mTac + "," + mEarfcn);
            mtv.append("  定位时间:" + ldate + "\n");
            mtv.append("  " + "mMcc = " + mMcc + "\n");
            mtv.append("  " + "mMnc = " + mMnc + "\n");
            mtv.append("  " + "mCi = " + mCi + "\n");
            mtv.append("  " + "mPci = " + mPci + "\n");
            mtv.append("  " + "mTac = " + mTac + "\n");
            mtv.append("  " + "mEarfcn = " + mEarfcn + "\n");
        } else {
            Toast.makeText(getApplicationContext(), "仅支持电信4G", Toast.LENGTH_SHORT).show();
            return null;
        }
        CellLocation cel = tel.getCellLocation();

        if (tel.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {//如果是电信卡的话
            CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cel;
            // mMcc=2147483647 mMnc=2147483647 mCi=2147483647 mPci=159 mTac=2147483647 mEarfcn=2452
            cid = cdmaCellLocation.getBaseStationId();
            lac = cdmaCellLocation.getNetworkId();
            //Toast.makeText(getApplicationContext(), cdmaCellLocation.toString(), Toast.LENGTH_SHORT).show();
        } else {//如果是移动和联通的话  移动联通一致
            GsmCellLocation gsmCellLocation = (GsmCellLocation) cel;
            cid = gsmCellLocation.getCid();
            lac = gsmCellLocation.getLac();
            //Toast.makeText(getApplicationContext(), gsmCellLocation.toString(), Toast.LENGTH_SHORT).show();
        }

        latLongString = "纬度:" + lat + "\n经度:" + lng + "\ncid:" + cid + "lac:" + lac + "\n";
        System.out.println("经度:" + lng + "纬度:" + lat);
    } else {
        mtv.append("  启动时间:" + date + "\n");
        latLongString = "无法获取地理信息,请稍后...";
    }
    if (lat != 0) {
        System.out.println("--------反馈信息----------" + String.valueOf(lat));
    }
    setmessage.setHint(latLongString);
    mtv.append("  " + latLongString + "\n");
    //Toast.makeText(getApplicationContext(), latLongString , Toast.LENGTH_SHORT).show();

    return location;

}

// 设置监听器,自动更新的最小时间为间隔N秒(1秒为1*1000,这样写主要为了方便)或最小位移变化超过N米
public final LocationListener mLocationListener01 = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        updateToNewLocation(location);
    }


    @Override
    public void onProviderDisabled(String provider) {
        updateToNewLocation(null);
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
};
// 设置监听器,自动更新的最小时间为间隔N秒(1秒为1*1000,这样写主要为了方便)或最小位移变化超过N米
public final LocationListener mLocationListener02 = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        updateToNewLocation(location);
    }


    @Override
    public void onProviderDisabled(String provider) {
        updateToNewLocation(null);
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
};

@Override
public void onClick(View v) {
    switch (v.getId()) {
        /*
        case R.id.main_btnServiceStart: {

            break;
        }
        case R.id.main_btnServiceStop:{
            //解除绑定
            unbindService(serviceConnection);
            break;
        }
        case R.id.main_btnServiceStatus:{
            int count = myBinder.getCount();
            Toast.makeText(MainActivityTwo.this, "Service的count值:" + count, Toast.LENGTH_SHORT).show();
            break;
        }
        default:break;

         */
    }
}

public String getCellInfo(CellInfo cellInfo) {
    String additional_info = "";
    if (cellInfo instanceof CellInfoGsm) {
        CellInfoGsm cellInfoGsm = (CellInfoGsm) cellInfo;
        CellIdentityGsm cellIdentityGsm = cellInfoGsm.getCellIdentity();
        additional_info = "cell CellInfoGsm " + cellIdentityGsm.getCid() + "\n"
                + "Mobile country code " + cellIdentityGsm.getMcc() + "\n"
                + "Mobile network code " + cellIdentityGsm.getMnc() + "\n"
                + "local area " + cellIdentityGsm.getLac() + "\n";
    } else if (cellInfo instanceof CellInfoLte) {
        CellInfoLte cellInfoLte = (CellInfoLte) cellInfo;
        //cellInfoLte.getCellIdentity()
        CellIdentityLte cellIdentityLte = cellInfoLte.getCellIdentity();
        if (ldate == null) ldate = new Date();

        // mMcc=2147483647 mMnc=2147483647 mCi=2147483647 mPci=159 mTac=2147483647 mEarfcn=2452
        mtv.setText("");
        mtv.append("  启动时间:" + date + "\n");
        mMcc = cellIdentityLte.getMcc();
        mMnc = cellIdentityLte.getMnc();
        mCi = cellIdentityLte.getCi();
        mPci = cellIdentityLte.getPci();
        mTac = cellIdentityLte.getTac();
        mEarfcn = cellIdentityLte.getEarfcn();

        mtv.append("  定位时间:" + ldate + "\n");
        mtv.append("  " + "mMcc = " + mMcc + "\n");
        mtv.append("  " + "mMnc = " + mMnc + "\n");
        mtv.append("  " + "mCi = " + mCi + "\n");
        mtv.append("  " + "mPci = " + mPci + "\n");
        mtv.append("  " + "mTac = " + mTac + "\n");
        mtv.append("  " + "mEarfcn = " + mEarfcn + "\n");
        additional_info = "cell CellInfoLte " + cellIdentityLte.getCi() + "\n"
                + "Mobile country code " + cellIdentityLte.getMcc() + "\n"
                + "Mobile network code " + cellIdentityLte.getMnc() + "\n"
                + "physical cell " + cellIdentityLte.getPci() + "\n"
                + "Tracking area code " + cellIdentityLte.getTac() + "\n";
    } else if (cellInfo instanceof CellInfoWcdma) {
        CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) cellInfo;
        CellIdentityWcdma cellIdentityWcdma = cellInfoWcdma.getCellIdentity();
        additional_info = "cell CellInfoWcdma " + cellIdentityWcdma.getCid() + "\n"
                + "Mobile country code " + cellIdentityWcdma.getMcc() + "\n"
                + "Mobile network code " + cellIdentityWcdma.getMnc() + "\n"
                + "local area " + cellIdentityWcdma.getLac() + "\n";
    }
    return additional_info;
}

//弹出来编辑窗口
private void editCell() {
    viewp = LayoutInflater.from(this).inflate(R.layout.dialog_input, null);
    peditText = viewp.findViewById(R.id.et_content);
    setmessage = viewp.findViewById(R.id.setmessage);
    alertDialog = new AlertDialog.Builder(this);
    alertDialog.setCancelable(false);

    tel = (TelephonyManager) getSystemService(this.TELEPHONY_SERVICE);
    locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    Activity#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for Activity#requestPermissions for more details.
        requestRxPermissions(Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION);
        return;
    }

    //创建一个criteria对象
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    //设置不需要获取海拔方向数据
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    //设置允许产生资费
    criteria.setCostAllowed(true);
    //要求低耗电
    //criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = locationManager.getBestProvider(criteria, true);
    Log.i("Tobin", "Location Provider is " + provider);
    Location location = locationManager.getLastKnownLocation(provider);
    System.out.println("star");
    if (location == null) {
        System.out.println("1null");
        location = getLastKnownLocation(locationManager);
    }
    if (location != null) {
        System.out.println("3null" + location.getLatitude() + "," + location.getLongitude());
        // 耗时操作
        //strLocation += " " + convertAddress(context, location.getLatitude(),location.getLongitude());

    } else {
        System.out.println("2null");
    }


    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, mLocationListener01);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, mLocationListener02);
    //加载编辑界面
    peditText.setHint("暂时未获取到数据请等待......");
    //peditText.setText("460,11,65471282,203,15952,1850");

    alertDialog.setTitle("记录当前位置");
    /*
    alertDialog.setMessage("完整基站经纬度数据是下面几个的数值mnc网络类型,lac基站大区编号,cellid基站编号,gps_lon经度,gps_lat纬度"  + "\n"
            +"基站编号和地理位置是对应的同样自然对应经纬度" + "\n"
            +"mnc,lac,cellid|gps_lon,gps_lat,例子1包含全部数据(1,9523,1275|4.090919,22.554522)" + "\n" +
            "简化版例子2只包含经纬度(4.090919,22.554522)"+ "\n" +"恢复默认里面夹杂一个字母就恢复默认随机位置例如1,A9523,1275|4.090919,22.554522");

     */
    alertDialog.setMessage("当前仅支持电信4G例子更改位置后" + "\n" + "重启完毕后一定要关闭WIFI");
    alertDialog.setView(viewp).setNegativeButton("确定-一旦设置全部记录生效", new DialogInterface.OnClickListener() {
        //alertDialog.setTitle("标题");

        @Override
        public void onClick(DialogInterface dialog, int which) {


            Toast.makeText(MainActivity.this, "设置成功", Toast.LENGTH_SHORT).show();


        }
    }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "被取消保持上一次状态", Toast.LENGTH_SHORT).show();
        }
    }).create();
    alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            //处理监听事件
            locationManager.removeUpdates(mLocationListener01);
            locationManager.removeUpdates(mLocationListener02);
        }
    });
    alertDialog.show();
}

/**
 * 使用正则表达式来判断字符串中是否包含字母
 * @param str 待检验的字符串
 * @return 返回是否包含
 * true: 包含字母 ;false 不包含字母
 */
public boolean judgeContainsStr(String str) {
    String regex = ".*[a-zA-Z]+.*";
    Matcher m = Pattern.compile(regex).matcher(str);
    return m.matches();
}

private Location getLastKnownLocation(LocationManager locationManager) {
    List<String> providers = locationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        //requestRxPermissions(Manifest.permission.RECORD_AUDIO);


        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return null;
        }
        Location l = locationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}

//请求权限
public void requestRxPermissions(String... permissions) {
    RxPermissions rxPermissions = new RxPermissions(this);
    rxPermissions.request(permissions).subscribe(new Consumer<Boolean>() {
        @Override
        public void accept(@NonNull Boolean granted) throws Exception {
            if (granted){
                editCell();
                //Toast.makeText(MainActivity.this, "已获取权限", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(MainActivity.this, "已拒绝一个或以上权限", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
















<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值