为什么我的Map在获得位置许可后没有初始化?

zfycwa2u  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(326)

用户第一次打开my mapsactivity时,会向其请求位置权限。然后它应该在不同的位置用标记开始我的卫星视图Map。但是,它会打开一个没有“我的标记”的通用googleMap,但是如果您随后退出该活动,并在授予位置权限后再次启动它,则可以正常工作。我很确定它没有调用我的initmap()函数,因此也没有调用onmapready(googlemap,googlemap)函数,在该函数中,Map被设置为卫星视图并添加了标记。我很确定在onrequestpermissionsresult()函数中,它没有在应该调用initmap()函数时调用它,但我不知道为什么?

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapClickListener {

    @Override
    public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
        mMap = googleMap;
        Log.d("map", mMap.toString());
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        if (mLocationPermissionsGranted) {
            Log.d("map", "location permission granted");
            getDeviceLocation();
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);
            this.mMap.setOnMapClickListener(this);
            init();
        }
        myReference = FirebaseDatabase.getInstance().getReference().child("garbageSpots");
        myReference.addValueEventListener(stateValueEventListener4 = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot children : dataSnapshot.getChildren()) {
                    LatLng coords = new LatLng(Double.parseDouble(children.child("lat").getValue().toString()), Double.parseDouble(children.child("long").getValue().toString()));
                    MarkerOptions options = new MarkerOptions().title(children.getKey()).position(coords);
                    mMap.addMarker(options);
                    Log.d("map", "marker for loop");
                }
                Log.d("map", "end of mk for loop");
                myReference.removeEventListener(stateValueEventListener4);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("The read failed: " + databaseError.getCode());
            }
        });
        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Intent i = new Intent(MapsActivity.this, InfoWindowActivity.class);
                LatLng latLng = marker.getPosition();
                String title = marker.getTitle();
                i.putExtra("location", latLng);
                i.putExtra("title", title);
                startActivity(i);
                return false;
            }
        });
    }

    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 15f;
    private DatabaseReference myReference;
    private ValueEventListener stateValueEventListener4;
    private EditText mSearchText;
    private ImageView mGps;
    private Boolean mLocationPermissionsGranted = false;
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationProviderClient;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        mSearchText = findViewById(R.id.inputSearch);
        mGps = findViewById(R.id.ic_gps);
        Log.d("map", "onCreate");
        getLocationPermission();
    }

    private void init(){
        Log.d("map", "init now");
        mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || keyEvent.getAction() == KeyEvent.ACTION_DOWN
                        || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
                    Log.d("map", "actionId in init");
                    geoLocate();
                }

                return false;
            }
        });
        mGps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDeviceLocation();
            }
        });

        hideSoftKeyboard();
    }

    private void geoLocate() {
        Log.d("map", "geoLocate start");
        String searchString = mSearchText.getText().toString();
        Geocoder geocoder = new Geocoder(MapsActivity.this);
        List<Address> list = new ArrayList<>();
        try{
            list = geocoder.getFromLocationName(searchString, 1);
        }catch (IOException e){
            Log.d("map", "geoLocate catch error");
        }

        if(list.size() > 0){
            Address address = list.get(0);
            moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), DEFAULT_ZOOM,
                    address.getAddressLine(0));
        }
    }

    private void getDeviceLocation(){
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapsActivity.this);
        try{
            if(mLocationPermissionsGranted){
                final Task location = mFusedLocationProviderClient.getLastLocation();
                Log.d("map", "GDL mLPG");
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        Log.d("map", "GDL on complete");
                        if(task.isSuccessful()){
                            Log.d("map", "GDL on success");
                            Location currentLocation = (Location)task.getResult();
                            moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
                                    DEFAULT_ZOOM,
                                    "My Location");
                        }else{
                            Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }catch (SecurityException e){
            Log.d("map", "getDeviceLocation catch error");
        }
    }

    private void moveCamera(LatLng latLng, float zoom, String title){
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
        if(!title.equals("My Location")){
            MarkerOptions options = new MarkerOptions()
                    .position(latLng)
                    .title(title);
            mMap.addMarker(options);
        }
        hideSoftKeyboard();
    }

    private void initMap(){
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        Log.d("map", mapFragment + " initMap");
        mapFragment.getMapAsync(MapsActivity.this);
    }

    private void getLocationPermission(){
        Log.d("map", "getLocationPermission start");
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};
        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            Log.d("map", "first if");
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                    COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                Log.d("map", "second if");
                mLocationPermissionsGranted = true;
                Log.d("map", mLocationPermissionsGranted.toString() + " mLPG string");
                initMap();
            }else{
                ActivityCompat.requestPermissions(this,
                        permissions,
                        LOCATION_PERMISSION_REQUEST_CODE);
                Log.d("map", "second if failed");
            }
        }else{
            Log.d("map", "first if failed");
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
            Log.d("map", String.valueOf(LOCATION_PERMISSION_REQUEST_CODE) + " location permission request code");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d("map", "ORPR");
        mLocationPermissionsGranted = false;
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0) {
                    for(int i = 0; i < grantResults.length; i++){
                        if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                            Log.d("map", String.valueOf(grantResults[i]));
                            Log.d("map", "false permission");
                            mLocationPermissionsGranted = false;
                            return;
                        }
                    }
                    mLocationPermissionsGranted = true;
                    Log.d("map", "initORPR");
                    initMap();
                }
            }
        }
    }
}

这是我的日志

2020-11-23 13:21:58.862 30494-30494/com.garbagespots.garbagespotsapp D/map: onCreate
2020-11-23 13:21:58.862 30494-30494/com.garbagespots.garbagespotsapp D/map: getLocationPermission start
2020-11-23 13:21:58.863 30494-30494/com.garbagespots.garbagespotsapp D/map: first if failed
2020-11-23 13:21:58.896 30494-30494/com.garbagespots.garbagespotsapp D/map: 1234 location permission request code
2020-11-23 13:21:58.926 30494-30494/com.garbagespots.garbagespotsapp D/ViewRootImpl@42a73ef[MapsActivity]: setView = DecorView@f405efc[MapsActivity] TM=true MM=false
2020-11-23 13:21:58.993 30494-30494/com.garbagespots.garbagespotsapp D/ViewRootImpl@42a73ef[MapsActivity]: dispatchAttachedToWindow
2020-11-23 13:21:59.049 30494-30494/com.garbagespots.garbagespotsapp D/ViewRootImpl@42a73ef[MapsActivity]: Relayout returned: old=[0,0][0,0] new=[0,0][1080,1920] result=0x7 surface={valid=true 486528770048} changed=true
2020-11-23 13:21:59.244 30494-30494/com.garbagespots.garbagespotsapp D/ViewRootImpl@42a73ef[MapsActivity]: MSG_RESIZED_REPORT: frame=Rect(0, 0 - 1080, 1920) ci=Rect(0, 72 - 0, 0) vi=Rect(0, 72 - 0, 0) or=1
2020-11-23 13:21:59.244 30494-30494/com.garbagespots.garbagespotsapp D/ViewRootImpl@42a73ef[MapsActivity]: MSG_WINDOW_FOCUS_CHANGED 1
2020-11-23 13:21:59.280 30494-30494/com.garbagespots.garbagespotsapp D/ViewRootImpl@42a73ef[MapsActivity]: MSG_WINDOW_FOCUS_CHANGED 0
2020-11-23 13:22:04.836 30494-30499/com.garbagespots.garbagespotsapp I/zygote64: Compiler allocated 6MB to compile void com.google.maps.api.android.lib6.gmm6.vector.bs.c(javax.microedition.khronos.opengles.GL10)
2020-11-23 13:22:12.289 30494-30494/com.garbagespots.garbagespotsapp D/ViewRootImpl@42a73ef[MapsActivity]: MSG_WINDOW_FOCUS_CHANGED 1
2020-11-23 13:22:12.353 30494-30494/com.garbagespots.garbagespotsapp D/map: ORPR
2020-11-23 13:22:12.353 30494-30494/com.garbagespots.garbagespotsapp D/map: -1
2020-11-23 13:22:12.353 30494-30494/com.garbagespots.garbagespotsapp D/map: false permission

这是我的名单

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

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".InstructionsActivity"
            android:parentActivityName=".HomePage"
            android:screenOrientation="portrait"/>
        <activity
            android:name=".PictureActivity"
            android:parentActivityName=".InfoWindowActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".ReportActivity"
            android:parentActivityName=".InfoWindowActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".CleanedUpActivity"
            android:parentActivityName=".InfoWindowActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".InfoWindowActivity"
            android:parentActivityName=".MapsActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".SignupActivity"
            android:parentActivityName=".WelcomeActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".WelcomeActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SpotAdderActivity"
            android:label="@string/title_activity_spot_adder"
            android:parentActivityName=".MapsActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".ProfileActivity"
            android:label="@string/title_activity_profile"
            android:parentActivityName=".HomePage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".HomePage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".LoginActivity"
            android:label="@string/title_activity_login"
            android:parentActivityName=".WelcomeActivity"
            android:screenOrientation="portrait" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyAF4V4wLa4OioU_taKsh59BfTVs1i02vgA" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps"
            android:parentActivityName=".InstructionsActivity"
            android:screenOrientation="portrait"/>
    </application>
</manifest>
laximzn5

laximzn51#

补充:

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

在我的名单上,它起了作用

相关问题