2016-04-08 57 views
2

我試圖在加載我的地​​圖活動時出現「我的位置」按鈕。這是我的代碼,使我的活動放大到當前位置的按鈕沒有出現。我需要更改我的代碼才能使其工作?Android 6上的setMyLocationEnabled()錯誤

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 
private static final String FIREBASE_URL="https://********.firebaseio.com/"; 
private Firebase firebaseRef; 
private LocationManager locationManager; 
private GoogleMap mMap; 
SupportMapFragment mapFrag; 
boolean bPermissionGranted; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps2); 
    Firebase.setAndroidContext(this); 
    firebaseRef = new Firebase(FIREBASE_URL); 
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     bPermissionGranted = 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); 





    } 
private void setUpMapIfNeeded() { 
    if (mMap == null) { 
     // Try to obtain the map from the SupportMapFragment. 
     mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
       .getMap(); 

     if (mMap != null) { 


      CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(32.065483, 34.824550)); 
      CameraUpdate zoom = CameraUpdateFactory.zoomTo(10); 
      mMap.moveCamera(center); 
      mMap.animateCamera(zoom); 

     } 
    } 
} 

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

     // Should we show an explanation? 
     if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
       Manifest.permission.ACCESS_FINE_LOCATION)) { 

      // Show an expanation 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. 
      // TODO: Prompt with explanation! 

      //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, yay! 
       if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && 
         ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
        mMap.setMyLocationEnabled(true); 
       } 
      } else { 
       // permission denied, boo! Disable the 
       // functionality that depends on this permission. 
       Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); 
      } 
      return; 
     } 

    } 
} 


@Override 
public void onMapReady(final GoogleMap googleMap) { 

    mMap=googleMap; 

    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     if (bPermissionGranted) { 
      //User has previously accepted this permission 
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && 
        ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
       mMap.setMyLocationEnabled(true); 
      } 
     } 
    } 
    else { 
     //Not in api-23, no need to prompt 
     mMap.setMyLocationEnabled(true); 
    } 

    firebaseRef.addListenerForSingleValueEvent(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 

      for (DataSnapshot child : dataSnapshot.child("users").getChildren()) { 


       String rightLocation = child.child("location_right").getValue().toString(); 
       String leftLocation = child.child("location_left").getValue().toString(); 

       double location_left = Double.parseDouble(leftLocation); 
       double location_right = Double.parseDouble(rightLocation); 
       String party_title = child.child("party/party_title").getValue().toString(); 
       LatLng cod = new LatLng(location_left, location_right); 
       googleMap.addMarker(new MarkerOptions().position(cod).title(party_title)); 


      } 
     } 

     @Override 
     public void onCancelled(FirebaseError firebaseError) { 

     } 
    }); 
} 
} 

回答

3

這是我other answer that also requests location updates的簡化版本。

關鍵是在撥打電話setMyLocationEnabled()之前確保用戶已經授予您許可。

這也有可能是用戶沒有按時間onMapReady()接受許可提示被稱爲(最有可能首先推出的應用程序),因此有在的情況下onRequestPermissionsResult()回調setMyLocationEnabled()另一個呼叫用戶接受許可。

首先,確保你有(外部應用程序標記的)在AndroidManifest.xml中的權限:

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

這是一個完整的活動類,會爲你工作:

public class MapLocationActivity extends AppCompatActivity 
     implements OnMapReadyCallback { 

    GoogleMap mGoogleMap; 
    SupportMapFragment mapFrag; 

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

     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      checkLocationPermission(); 
     } 

     mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
     mapFrag.getMapAsync(this); 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mGoogleMap = googleMap; 
     mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 

     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      //User has previously accepted this permission 
      if (ActivityCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
       mGoogleMap.setMyLocationEnabled(true); 
      } 
     } else { 
      //Not in api-23, no need to prompt 
      mGoogleMap.setMyLocationEnabled(true); 
     } 
    } 

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 

    public boolean checkLocationPermission() { 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Should we show an explanation? 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission.ACCESS_FINE_LOCATION)) { 

       // Show an expanation 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. 
       // TODO: Prompt with explanation! 

       //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, yay! 
        if (ActivityCompat.checkSelfPermission(this, 
          Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
         mGoogleMap.setMyLocationEnabled(true); 
        } 
       } else { 
        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); 
       } 
       return; 
      } 

     } 
    } 
} 

如果您撤銷許可:

enter image description here

它會再次提示:

enter image description here

+0

我試過了你的答案,但每當這行寫入時都有一個錯誤消息:'mMap.setMyLocationEnabled(true);'。錯誤表示:_call需要可能被用戶拒絕的權限:代碼應明確檢查權限是否可用(使用'checkPermission')或明確處理潛在的'SecurityExpection'_ – olash12345

+0

而且它甚至不會要求我使用我的位置的權限在我的手機中。 – olash12345

+0

@ olash12345我剛剛更新了答案,以進一步簡化它。通過添加必要的檢查,不需要布爾值。我只是在6.0.1版本的Nexus 5和6.0.1版本的Nexus 6上進行了測試,它會提示輸入位置權限,然後啓用按預期工作的MyLocaction按鈕。 –

0

在if和else塊中使用相同的條件。

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) 

所以,如果你的上述條件不是真的,那麼在你的else塊中相同的條件會如何變爲真。這就是因爲你的條件是錯誤的, mMap.setMyLocationEnabled(true);永遠不會被執行。

我想你想在其他塊做什麼是要求權限,如果它不存在。因此,它會改變這樣的 -

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
        mMap.setMyLocationEnabled(true); 
    } else{ 

     ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, <request_code>); 
    } 

並實行onRequestPermissionsResult回調

@Override 
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     switch (requestCode) { 
      case <request_code>: 
       if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { 
        mMap.setMyLocationEnabled(true); 
       } 
       break; 
     } 
    } 
+0

嘿,我已經試過你的答案,並有出現兩個錯誤: 1)什麼是你想在這一行'情況做:'?它會導致錯誤。 2)該行顯示錯誤:'mMap.setMyLocationEnabled(true);'說:調用需要權限,可能會被用戶拒絕:代碼應明確檢查權限是否可用(使用'checkPermission')或明確處理潛在的'SecurityExpection' – olash12345