mashmallow上的Android运行时位置权限导致应用程序崩溃
我正在做一个基于地图的应用程序,需要位置许可。它工作正常,但问题是,对于棉花糖运行时权限,当权限对话框打开时,应用程序就会崩溃 以下是完整的代码:mashmallow上的Android运行时位置权限导致应用程序崩溃,android,google-maps,location,android-6.0-marshmallow,runtime-permissions,Android,Google Maps,Location,Android 6.0 Marshmallow,Runtime Permissions,我正在做一个基于地图的应用程序,需要位置许可。它工作正常,但问题是,对于棉花糖运行时权限,当权限对话框打开时,应用程序就会崩溃 以下是完整的代码: public class MapsActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListe
public class MapsActivity extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, SensorEventListener, GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private ClusterManager<MyItem> mClusterManager;
/* @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}*/
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_maps,container,false);
try {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
}catch (Exception e){
e.printStackTrace();
}
SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
//getAllMarkerData();
return view;
}
/**
* 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;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).
title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap = googleMap;
// mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
return;
}else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
setUpClusterer();
//mClusterManager = new ClusterManager<MyItem>(this, mMap);
//addItems();
}
private void setUpClusterer() {
// Position the map.
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.503186, -0.126446), 10));
// Initialize the manager with the context and the map.
// (Activity extends context, so we can pass 'this' in the constructor.)
mClusterManager = new ClusterManager<MyItem>(getActivity(), mMap);
// Point the map's listeners at the listeners implemented by the cluster
// manager.
mMap.setOnCameraIdleListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
// Add cluster items (markers) to the cluster manager.
getAllMarkerData();
}
private void addItems() {
// Set some lat/lng coordinates to start with.
double lat = 51.5145160;
double lng = -0.1270060;
// Add ten cluster items in close proximity, for purposes of this example.
for (int i = 0; i < 10; i++) {
double offset = i / 60d;
lat = lat + offset;
lng = lng + offset;
MyItem offsetItem = new MyItem(lat, lng);
mClusterManager.addItem(offsetItem);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@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 boolean onMarkerClick(Marker marker) {
return false;
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.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(getActivity(),
android.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(getActivity(), "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.
}
}
private void getAllMarkerData() {
final ApplicationConfig service = AppClient.getApiService();
Call<ArrayList<AllDataContent>> list = service.getAllDatas();
list.enqueue(new Callback<ArrayList<AllDataContent>>() {
@Override
public void onResponse(Call<ArrayList<AllDataContent>> call, Response<ArrayList<AllDataContent>> response) {
if (response.isSuccessful()){
Toast.makeText(getActivity(),response.body().toString(), Toast.LENGTH_SHORT).show();
ArrayList<AllDataContent> arrayListAllDataContent = response.body();
for (int i = 0; i <arrayListAllDataContent.size() ; i++) {
arrayListAllDataContent.get(i).getLatitude();
arrayListAllDataContent.get(i).getLongitude();
Double lattitude = Double.parseDouble( arrayListAllDataContent.get(i).getLatitude());
Double longitude = Double.parseDouble( arrayListAllDataContent.get(i).getLongitude());
MyItem offsetItem = new MyItem(lattitude, longitude);
mClusterManager.addItem(offsetItem);
LatLng hospitalMarker = new LatLng(lattitude, longitude);
Drawable TRANSPARENT_DRAWABLE = new ColorDrawable(Color.TRANSPARENT);
mCurrLocationMarker = mMap.addMarker(new MarkerOptions()
.position(hospitalMarker)
.title(arrayListAllDataContent.get(i).getOperatorName())
.snippet(arrayListAllDataContent.get(i).getAddress())
.alpha(0.8f));
//.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mCurrLocationMarker.setTag(arrayListAllDataContent.get(i).getId());
}
}else {
Toast.makeText(getActivity(),"un suceess", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ArrayList<AllDataContent>> call, Throwable t) {
Toast.makeText(getActivity(),"error", Toast.LENGTH_SHORT).show();
}
});
}
公共类MapsActivity扩展了MapReadyCallback上的片段实现,
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener,
LocationListener、SensorEventListener、GoogleMap.OnMarkerClickListener{
私有谷歌地图;
GoogleapClient MGoogleapClient;
位置mLastLocation;
标记器mCurrLocationMarker;
位置请求mLocationRequest;
私人群集管理器McClusterManager;
/*@覆盖
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
}*/
@可空
@凌驾
创建视图时的公共视图(LayoutFlater充气机、@Nullable ViewGroup容器、@Nullable Bundle savedInstanceState){
视图=充气机。充气(右布局。活动图,容器,假);
试一试{
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
checkLocationPermission();
}
}捕获(例外e){
e、 printStackTrace();
}
SupportMapFragment mapFragment=((SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map));
getMapAsync(这个);
//getAllMarkerData();
返回视图;
}
/**
*一旦可用,就可以操纵贴图。
*当映射准备好使用时,将触发此回调。
*这是我们可以添加标记或线条、添加侦听器或移动摄影机的地方。在这种情况下,
*我们只是在澳大利亚悉尼附近加了一个标记。
*如果设备上未安装Google Play服务,系统将提示用户安装
*它位于SupportMapFragment内。此方法仅在用户
*已安装Google Play服务并返回应用程序。
*/
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
//在Sydney添加一个标记并移动相机
悉尼LatLng=新LatLng(-34151);
mMap.addMarker(新的MarkerOptions().position(悉尼)。
标题(“悉尼的标志”);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(悉尼));
mMap=谷歌地图;
//mMap.setMapType(GoogleMap.MAP\u TYPE\u HYBRID);
if(ActivityCompat.checkSelfPermission(getActivity(),android.Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(getActivity(),android.Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
buildGoogleAppClient();
mMap.setMyLocationEnabled(真);
返回;
}否则{
buildGoogleAppClient();
mMap.setMyLocationEnabled(真);
}
setupcluster();
//mClusterManager=newclustermanager(这个,mMap);
//addItems();
}
私有void setupcluster(){
//定位地图。
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(新LatLng(51.503186,-0.126446),10));
//使用上下文和映射初始化管理器。
//(活动扩展了上下文,因此我们可以在构造函数中传递“this”。)
mClusterManager=newclustermanager(getActivity(),mMap);
//将映射的侦听器指向集群实现的侦听器
//经理。
mMap.setonCameraideListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
//将群集项目(标记)添加到群集管理器。
getAllMarkerData();
}
私有void附加项(){
//首先设置一些lat/lng坐标。
双lat=51.5145160;
双液化天然气=-0.1270060;
//为了本例的目的,添加十个近距离的集群项目。
对于(int i=0;i<10;i++){
双偏移=i/60d;
横向=横向+偏移;
液化天然气=液化天然气+补偿;
MyItem offsetItem=新的MyItem(lat、lng);
mClusterManager.addItem(offsetItem);
}
}
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(getActivity())
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@凌驾
传感器更改时的公共无效(传感器事件传感器事件){
}
@凌驾
精度更改时的公共无效(传感器,int i){
}
@凌驾
未连接的公共无效(@Nullable Bundle){
mlLocationRequest=新位置请求();
mlLocationRequest.setInterval(1000);
mlLocationRequest.setFastTestInterval(1000);
mLocationRequest.setPriority(位置请求、优先级、平衡、功率、精度);
if(ContextCompat.checkSelfPermission(getActivity()),
android.Manifest.permission.ACCESS\u很好