如果我們沒有特別提供授權的功能的話,使用者是無法使用的,除非去 Android 的應用程式設定去將定位打開(不是開啟手機的定位功能喔!)是應用程式自己可以使用定位的授權。
早期我們要取得定位服務只需要
lms = (LocationManager) getSystemService(LOCATION_SERVICE);
但是在 android 6 之後,android studio 就會要求我們要做檢查的動作:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //如果沒有授權使用定位就會跳出來這個
            // TODO: Consider calling
            //    ActivityCompat#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 ActivityCompat#requestPermissions for more details.
            requestLocationPermission(); // 詢問使用者開啟權限
            return;
        }
所以我們必須多做一段這個:
private void requestLocationPermission() {
        // 如果裝置版本是6.0(包含)以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 取得授權狀態,參數是請求授權的名稱
            int hasPermission = checkSelfPermission(
                    Manifest.permission.ACCESS_FINE_LOCATION);
            // 如果未授權
            if (hasPermission != PackageManager.PERMISSION_GRANTED) {
                // 請求授權
                //     第一個參數是請求授權的名稱
                //     第二個參數是請求代碼
                requestPermissions(
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        REQUEST_FINE_LOCATION_PERMISSION);
            }
            else {
                // 啟動地圖與定位元件
            }
        }
    }
Android 6 Tutorial 第四堂(3)讀取裝置目前的位置 - Google Services Location
 


