在真实手机中查看时位置崩溃

时间:2018-02-15 21:07:07

标签: android google-maps-android-api-2

我正在使用此片段在我当前的位置上添加标记。

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;


public class SecondFragment extends Fragment implements OnMapReadyCallback {

    private GoogleMap mMap;

    public GoogleMap getMap() {
        return mMap;
    }
    public static SecondFragment newInstance() {
        SecondFragment fragment = new SecondFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second, null, false);

        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        return view;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        double latitude=0.0;
        double longitude=0.0;


        LocationManager locationManager = (LocationManager)getActivity().getSystemService(getActivity().LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(getActivity(), new String[]
                    {android.Manifest.permission.ACCESS_FINE_LOCATION,
                            android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);

        }else {
            mMap.setMyLocationEnabled(true);

            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker");
            googleMap.addMarker(marker);

            CameraPosition cameraPosition = new CameraPosition.Builder().target(
                    new LatLng(latitude, longitude)).zoom(12).build();
            Toast.makeText(getContext(), String.valueOf(latitude), Toast.LENGTH_LONG).show();
            Toast.makeText(getContext(), String.valueOf(longitude), Toast.LENGTH_LONG).show();

            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
            googleMap.getUiSettings().setZoomGesturesEnabled(true);
            googleMap.getUiSettings().setCompassEnabled(true);
            googleMap.getUiSettings().setMyLocationButtonEnabled(true);
            googleMap.getUiSettings().setRotateGesturesEnabled(true);
        }
    }
}

我启用了这些权限

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

我正在使用播放服务27.

代码编译正常,在模拟器中,它没有崩溃。 (我不知道为什么在模拟器中,它不会显示地图,只是一个空白的屏幕,左下角有谷歌徽标。)

但是,如果我创建一个apk并将其放入真正的手机(nexus 5x)中,那就会崩溃。

在模拟器中,logcat不会显示任何错误。请帮助

1 个答案:

答案 0 :(得分:0)

您遇到此错误,因为getLastLocation返回null。首先,您必须检查手机GPS是否启用。

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(location!=null){
           latitude = location.getLatitude();
           longitude = location.getLongitude();
           MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker");
           googleMap.addMarker(marker);
        }

我建议您使用融合api提供程序来定位其耗尽电量并提供高精度

mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(MainActivity.this, new OnSuccessListener<android.location.Location>() {
                @Override
                public void onSuccess(android.location.Location location) {
                    if(location!=null){
                        try{
                            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                            Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());

                            String addresses = geocoder.getFromLocation(location.getLatitude(),
                                    location.getLongitude(), 1).get(0).getAddressLine(0);

                            marker_origin = new MarkerOptions().
                                    position(latLng).title(addresses)
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                            mMap.addMarker(marker_origin);
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f));


                            getPlacesData(latLng, "restaurant");
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            });

您可以查看下面的Android开发者文档

https://developer.android.com/training/location/retrieve-current.html