要在Android應用中展示GNSS狀態信息,您需要使用LocationManager
和GnssStatus.Callback
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
LocationManager
實例:LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
GnssStatus.Callback
實例,以便在GNSS狀態發生變化時接收回調:private GnssStatus.Callback gnssStatusCallback = new GnssStatus.Callback() {
@Override
public void onStarted() {
// GNSS已啟動
}
@Override
public void onStopped() {
// GNSS已停止
}
@Override
public void onFirstFix(int ttffMillis) {
// 第一次定位成功,ttffMillis為定位耗時(毫秒)
}
@Override
public void onSatelliteStatusChanged(GnssStatus status) {
// GNSS衛星狀態發生變化,可以獲取衛星數量、信號強度等信息
int satelliteCount = status.getSatelliteCount();
// ...
}
};
GnssStatus.Callback
:if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.registerGnssStatusCallback(gnssStatusCallback);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION_PERMISSION);
}
onRequestPermissionsResult
方法中處理權限請求結果:@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_LOCATION_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationManager.registerGnssStatusCallback(gnssStatusCallback);
} else {
// 權限被拒絕
}
}
}
onPause
方法中取消注冊GnssStatus.Callback
:@Override
protected void onPause() {
super.onPause();
locationManager.unregisterGnssStatusCallback(gnssStatusCallback);
}
現在,當GNSS狀態發生變化時,您將收到相應的回調。您可以根據需要更新UI或執行其他操作。