Android LocationManager.getBestProvider()返回NULL

Android LocationManager.getBestProvider()返回NULL
Android LocationManager.getBestProvider()返回NULL

『GPS』全球定位代碼,係『eclipse』移過蒞『Android Studio』, 發現getBestProvider()返回NULL. 源於冇『權限』 , 而『Android 6』後要人手獲得授權, 冇『權限』getBestProvider()永遠返回null. 係程式啟動檢查『權限』, 若冇『權限』提出請求伸請.

string GetBestProvider (Criteria criteria, bool enabledOnly)

『GPS』定位伸請『權限』

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

『權限』

Manifest.permission.ACCESS_FINE_LOCATION 高精度定位
Manifest.permission.ACCESS_COARSE_LOCATION 低精度定位

檢查『權限』

int coarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
int fine = ContextCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION);

返回值判斷係咪獲得『權限』

PackageManager.PERMISSION_GRANTED 有『權限』
PackageManager.PERMISSION_DENIED 冇『權限』

判斷有冇『權限』

if(coarse == PackageManager.PERMISSION_DENIED || fine == PackageManager.PERMISSION_DENIED )

請求伸請. context必需係Activity

String permission[] = new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions((Activity) context,permission,REQUEST_CODE_GPS);

GPS權限請求碼

public static int REQUEST_CODE_GPS = 156;

處理GPS授權回調, 係MainActivity判斷授權

@Override

public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults){

requestCode係權限請求碼

if(requestCode == GPS.REQUEST_CODE_GPS) {// 羅盤權限請求碼

判斷『權限』係咪獲得

if(grantResults[0] == PackageManager.PERMISSION_GRANTED &&

grantResults[1] == PackageManager.PERMISSION_GRANTED) { // 獲得授權

再次定位

GPS.UpdatesLocation();

交翻畀onRequestPermissionsResult()處理

   super.onRequestPermissionsResult(requestCode,permissions,grantResults);

}

 

 

發表評論