1

나는이 튜토리얼는 어떻게 모드를 기본적으로 형성 "높은 정확도/배터리 절약"할 위치 모드를 변경합니다 (장치 전용)

android google map tutorial

을 사용하여 현재 위치를 얻기 위해 구글 맵을 구현하기 위해 노력하고있어 문제는 현재 기기의 Google지도를 시작하고 Google 위치 서비스에 액세스 할 수있는 권한을 부여 할 때까지 현재 위치가 표시되지 않는다는 것입니다. 이 후 내 응용 프로그램은 현재 위치를 가져옵니다. 그리고 장치에서 위치 정보가 켜질 때까지 제대로 작동합니다. 위치를 사용 중지하면 다시 기기의 Google지도를 시작하고 Google 위치 서비스에 대한 권한을 부여해야합니다.

지침에 따라 이미 키를 생성했습니다.

기기 위치 모드에서 문제가 발견되었습니다. 기기 모드를 고정밀/배터리 절약으로 수동 변경하면 문제가 없습니다.

그래서 어떻게 모드를 기본적으로 형성 "높은 정확도/배터리 절약"할 위치 모드 변경 (기기 만) 프로그래밍 여기

은 활동 코드입니다 : 여기

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     LocationListener { 

    private GoogleMap mMap; 
    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    LocationRequest mLocationRequest; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      checkLocationPermission(); 
     } 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 
    } 


    /** 
    * Manipulates the map once available. 
    * This callback is triggered when the map is ready to be used. 
    * This is where we can add markers or lines, add listeners or move the camera. In this case, 
    * we just add a marker near Sydney, Australia. 
    * If Google Play services is not installed on the device, the user will be prompted to install 
    * it inside the SupportMapFragment. This method will only be triggered once the user has 
    * installed Google Play services and returned to the app. 
    */ 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 

     //Initialize Google Play Services 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (ContextCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       buildGoogleApiClient(); 
       mMap.setMyLocationEnabled(true); 
      } 
     } 
     else { 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 
     } 
    } 

    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 

     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(1000); 
     mLocationRequest.setFastestInterval(1000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
     } 

    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onLocationChanged(Location location) { 

     mLastLocation = location; 
     if (mCurrLocationMarker != null) { 
      mCurrLocationMarker.remove(); 
     } 

     //Place current location marker 
     LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
     MarkerOptions markerOptions = new MarkerOptions(); 
     markerOptions.position(latLng); 
     markerOptions.title("Current Position"); 
     markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
     mCurrLocationMarker = mMap.addMarker(markerOptions); 

     //move map camera 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); 

     //stop location updates 
     if (mGoogleApiClient != null) { 
      LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     } 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
    public boolean checkLocationPermission(){ 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Asking user if explanation is needed 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission.ACCESS_FINE_LOCATION)) { 

       // Show an explanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 

       //Prompt the user once explanation has been shown 
       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 


      } else { 
       // No explanation needed, we can request the permission. 
       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
      return false; 
     } else { 
      return true; 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        // permission was granted. Do the 
        // contacts-related task you need to do. 
        if (ContextCompat.checkSelfPermission(this, 
          Manifest.permission.ACCESS_FINE_LOCATION) 
          == PackageManager.PERMISSION_GRANTED) { 

         if (mGoogleApiClient == null) { 
          buildGoogleApiClient(); 
         } 
         mMap.setMyLocationEnabled(true); 
        } 

       } else { 

        // Permission denied, Disable the functionality that depends on this permission. 
        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); 
       } 
       return; 
      } 

      // other 'case' lines to check for other permissions this app might request. 
      // You can add here other case statements according to your requirement. 
     } 
    } 
} 

이됩니다 매니페스트 파일 코드 :

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.googlemap"> 

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 


    <permission 
     android:name="com.example.envent_pc03.googlemap.permission.MAPS_RECEIVE" 
     android:protectionLevel="signature" /> 
    <uses-permission android:name="com.example.googlemap.permission.MAPS_RECEIVE"/> 
    <uses-feature android:name="android.hardware.location.gps" /> 

    <uses-feature 
     android:glEsVersion="0x00020000" 
     android:required="true"/> 
    <!-- 
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use 
     Google Maps Android API v2, but you must specify either coarse or fine 
     location permissions for the 'MyLocation' functionality. 
    --> 
    <!--<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />--> 
    <!--<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />--> 
    <!--<uses-permission android:name="android.permission.INTERNET" />--> 
    <!--<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />--> 
    <!-- 
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use 
     Google Maps Android API v2, but you must specify either coarse or fine 
     location permissions for the 'MyLocation' functionality. 
    --> 
    <!--<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>--> 
    <!--<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />--> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 

     <!-- 
      The API key for Google Maps-based APIs is defined as a string resource. 
      (See the file "res/values/google_maps_api.xml"). 
      Note that the API key is linked to the encryption key used to sign the APK. 
      You need a different API key for each encryption key, including the release key that is used to 
      sign the APK for publishing. 
      You can define the keys for the debug and release targets in src/debug/ and src/release/. 
     --> 
     <meta-data 
      android:name="com.google.android.geo.API_KEY" 
      android:value="@string/google_maps_key" /> 

     <activity 
      android:name=".MapsActivity" 
      android:label="@string/title_activity_maps"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 
+0

이 장치를 실행중인 장치는 무엇입니까? –

+0

사용자의 지식없이 할 수 있는지 확실하지 않은 경우 (단, 사용자에게 확인 메시지를 보내고 리디렉션 또는 추가 탐색없이 사용 가능하도록 설정하는 방법) (http://stackoverflow.com/questions/28759454/enabling -location-with-mode-high-accuracy-or-battery-saving- 사용자 - 필요 없음/29002760 # 29002760) – user2450263

답변

0

위치 업데이트를 요청하기 전에 올바른 위치 설정이 pe인지 확인해야합니다 귀하의 요구 사항.

LocationSettingsRequest.Builder을 만들고 앱을 사용하게 될 그 LocationRequests 모두 추가 :

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest); 

확인 위치 설정은

PendingResult<LocationSettingsResult> result = 
     LocationServices.SettingsApi.checkLocationSettings(mGoogleClient, builder.build()); 

PendingResult 반환의를 사용하여, 만족 여부 클라이언트는 LocationSettingsResult 객체의 상태 코드를보고 위치 설정을 확인할 수 있습니다.

result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
    @Override 
    public void onResult(LocationSettingsResult result) { 
     final Status status = result.getStatus(); 
     final LocationSettingsStates = result.getLocationSettingsStates(); 
     switch (status.getStatusCode()) { 
      case LocationSettingsStatusCodes.SUCCESS: 
       // All location settings are satisfied. The client can initialize location 
       // requests here. 
       ... 
       break; 
      case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
       // Location settings are not satisfied. But could be fixed by showing the user 
       // a dialog. 
       try { 
        // Show the dialog by calling startResolutionForResult(), 
        // and check the result in onActivityResult(). 
        status.startResolutionForResult(
         MapsActivity.this, 
         REQUEST_CHECK_SETTINGS); 
       } catch (SendIntentException e) { 
        // Ignore the error. 
       } 
       break; 
      case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
       // Location settings are not satisfied. However, we have no way to fix the 
       // settings so we won't show the dialog. 
       ... 
       break; 
     } 
    } 
}); 

대화의 결과는 (INT, INT, 의도)

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    final LocationSettingsStates states = LocationSettingsStates.fromIntent(intent); 
    switch (requestCode) { 
     case REQUEST_CHECK_SETTINGS: 
      switch (resultCode) { 
       case Activity.RESULT_OK: 
        // All required changes were successfully made 
        ... 
        break; 
       case Activity.RESULT_CANCELED: 
        // The user was asked to change settings, but chose not to 
        ... 
        break; 
       default: 
        break; 
      } 
      break; 
    } 
} 

onActivityResult를 통해 반환 참고로, 아주 잘 경우를 설명 SettingsApi 문서를 읽을 수 있습니다.

또는 사용자를 직접 위치 설정 페이지로 리디렉션 할 수 있습니다.

int locationMode = Settings.Secure.getInt(activityUnderTest.getContentResolver(), Settings.Secure.LOCATION_MODE); 

가능한 반환 값은을 확인하십시오. 당신이 그렇게 조각을 클래스 또는 구글에서 지원 맵을 사용하는 것입니다 원인 여부를 여기

if(locationMode == LOCATION_MODE_HIGH_ACCURACY) { 
    //request location updates 
} else { //redirect user to settings page 
    startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
} 
0

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    locationrequest = new LocationRequest().create(); 
    locationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    locationrequest.setInterval(1000); 

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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. 
     return; 
    } 
    LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleApi, locationrequest, this); 
    Toast.makeText(context,"Location Connected and ready to publish",Toast.LENGTH_SHORT).show(); 
} 
0

시도는 XML에서 구글 맵을 변경합니다.