源码
package com.android.circlescalebar;import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.GnssClock;
import android.location.GnssMeasurement;
import android.location.GnssMeasurementsEvent;
import android.location.GnssStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;
import com.android.circlescalebar.data.GnssRawData;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;public class GpsActivity extends AppCompatActivity {public static final int LOCATION_CODE = 525;private LocationManager locationManager;private String locationProvider = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_gps);getLocation();GnssTest();}private void getLocation() {locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);//获取所有可用的位置提供器List<String> providers = locationManager.getProviders(true);if (providers.contains(LocationManager.GPS_PROVIDER)) {//如果是GPSlocationProvider = LocationManager.GPS_PROVIDER;} else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {//如果是NetworklocationProvider = LocationManager.NETWORK_PROVIDER;} else {Intent i = new Intent();i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);startActivity(i);}if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//获取权限(如果没有开启权限,会弹出对话框,询问是否开启权限)if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {//请求权限ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);} else {//监视地理位置变化locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);Location location = locationManager.getLastKnownLocation(locationProvider);if (location != null) {//输入经纬度Toast.makeText(this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show();}}} else {//监视地理位置变化locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);Location location = locationManager.getLastKnownLocation(locationProvider);if (location != null) {//不为空,显示地理位置经纬度Toast.makeText(this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show();}}}private void GnssTest() {if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return;}locationManager.registerGnssStatusCallback(mGNSSCallback, null); //卫星导航系统的状态发生变化时被调用locationManager.registerGnssMeasurementsCallback(mGnssMeasurementsListener, null); //卫星测量数据// 请求位置跟新,所有监听器的回调都必须通过此方法locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, locationListener);}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);switch (requestCode) {case LOCATION_CODE:if (grantResults.length > 0 && grantResults[0] == getPackageManager().PERMISSION_GRANTED&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {Toast.makeText(this, "申请权限", Toast.LENGTH_LONG).show();try {List<String> providers = locationManager.getProviders(true);if (providers.contains(LocationManager.NETWORK_PROVIDER)) {//如果是NetworklocationProvider = LocationManager.NETWORK_PROVIDER;} else if (providers.contains(LocationManager.GPS_PROVIDER)) {//如果是GPSlocationProvider = LocationManager.GPS_PROVIDER;}//监视地理位置变化locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);Location location = locationManager.getLastKnownLocation(locationProvider);if (location != null) {//不为空,显示地理位置经纬度Toast.makeText(GpsActivity.this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show();}} catch (SecurityException e) {e.printStackTrace();}} else {Toast.makeText(this, "缺少权限", Toast.LENGTH_LONG).show();finish();}break;}}@Overrideprotected void onDestroy() {super.onDestroy();locationManager.removeUpdates(locationListener);}public LocationListener locationListener = new LocationListener() {// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数@Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {}// Provider被enable时触发此函数,比如GPS被打开@Overridepublic void onProviderEnabled(String provider) {}// Provider被disable时触发此函数,比如GPS被关闭@Overridepublic void onProviderDisabled(String provider) {}//当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发@Overridepublic void onLocationChanged(Location location) {if (location != null) {//不为空,显示地理位置经纬度Toast.makeText(GpsActivity.this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show();}}};GnssStatus.Callback mGNSSCallback = new GnssStatus.Callback() {@Overridepublic void onSatelliteStatusChanged(@NonNull GnssStatus status) {super.onSatelliteStatusChanged(status);// get satellite countint satelliteCount = status.getSatelliteCount();int BDSatelliteCount = 0;int BDSInFix = 0;TextView sateCount = findViewById(R.id.sateCount);TextView satebeidou = findViewById(R.id.satebeidou);TextView satebeidoulocation = findViewById(R.id.satebeidoulocation);sateCount.setText("共收到卫星信号:" + satelliteCount + "个");if(satelliteCount > 0) {for (int i = 0; i < satelliteCount; i++) {// get satellite typeint type = status.getConstellationType(i);if(GnssStatus.CONSTELLATION_BEIDOU == type) {// increase if type == BEIDOUBDSatelliteCount++;if (status.usedInFix(i)) {BDSInFix++;}}}satebeidou.setText("北斗卫星有:" + BDSatelliteCount + "个");satebeidoulocation.setText("用于定位的北斗卫星有:" + BDSInFix + "个");}}};private final GnssMeasurementsEvent.Callback mGnssMeasurementsListener = new GnssMeasurementsEvent.Callback() {@Overridepublic void onGnssMeasurementsReceived(GnssMeasurementsEvent eventArgs) {super.onGnssMeasurementsReceived(eventArgs);GnssClock clock = eventArgs.getClock();Collection<GnssMeasurement> measurements = eventArgs.getMeasurements();List<Mea> mLst = new ArrayList<>();for (GnssMeasurement measurement : measurements) {GnssRawData data = new GnssRawData(measurement, clock);mLst.add(new Mea(data.getPRN(), data.getCarrierFrequencyHZ(), data.getPseudorange(),clock.getTimeNanos(), clock.getFullBiasNanos(), measurement.getReceivedSvTimeNanos()));}Collections.sort(mLst);StringBuilder builder = new StringBuilder();Locale locale = Locale.getDefault();builder.append(String.format(locale, "%5s%20s%20s\n", "SV", "Carrier(MHz)", "Value"));for (Mea m : mLst) {builder.append(String.format(locale, "%5s%20.3f%20.3f\n", m.getPRN(),m.getCarrier(), m.getPseudorange()));}runOnUiThread(new Runnable() {@Overridepublic void run() {TextView sate = findViewById(R.id.sate);sate.setText(builder.toString());}});}@Overridepublic void onStatusChanged(int status) {super.onStatusChanged(status);}};/*** 将 measurement排序(为了查看是否有多频)*/class Mea implements Comparable<Mea> {private final String prn;private final double carrier;private final double pseudorange;private final double TimeNanos;private final double FullBiasNanos;private final double ReceivedSvTimeNanos;public Mea(String prn, double carrier, double pseudorange, double TimeNanos,double FullBiasNanos, double ReceivedSvTimeNanos) {this.prn = prn;this.carrier = carrier;this.pseudorange = pseudorange;this.TimeNanos = TimeNanos;this.FullBiasNanos = FullBiasNanos;this.ReceivedSvTimeNanos = ReceivedSvTimeNanos;}@Overridepublic int compareTo(Mea o) {return this.prn.compareTo(o.prn);}public String getPRN() {return prn;}public double getCarrier() {return carrier;}public double getPseudorange() {return pseudorange;}public double getTimeNanos() {return TimeNanos;}public double getFullBiasNanos() {return FullBiasNanos;}public double getReceivedSvTimeNanos() {return ReceivedSvTimeNanos;}}
}