Google 地图无法访问我的 if 语句以获得权限

Google Maps not getting to my if statement for permissions

所以我正在将 google 映射实现到一个片段中。但是,我想检查是否已授予对其位置的许可。在 permission_granted 上测试我的 if 语句时,它只会使应用程序崩溃。即使我翻转 if 和 else 的内容,我仍然得到相同的结果。

更新代码

  public class ThirdFragment extends Fragment implements OnMapReadyCallback {
    View myView;
    private GoogleMap mMap;


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.third_layout, container, false);
        return myView;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        MapFragment mapFrag = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);


    }

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


        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
            Criteria criteria = new Criteria();
            LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
            String provider = locationManager.getBestProvider(criteria, false);
            Location location = locationManager.getLastKnownLocation(provider);
            double lat =  location.getLatitude();
            double lng = location.getLongitude();
            LatLng coordinate = new LatLng(lat, lng);
            CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 13);
            mMap.animateCamera(yourLocation);

        } else {
            AlertDialog alertDialogGPS = new AlertDialog.Builder(getActivity()).create();

            alertDialogGPS.setTitle("Info");
            alertDialogGPS.setMessage("Looks like you have not given GPS permissions. Please give GPS permissions and return back to the app.");
            alertDialogGPS.setIcon(android.R.drawable.ic_dialog_alert);
            alertDialogGPS.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    //dismiss();
                    Intent intentSettings = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                    startActivity(intentSettings);
                }
            });

            alertDialogGPS.show();
        }




    }


}

错误日志:

08/13 02:06:45: Launching MainActivity
$ adb shell am start -n "com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 9120 on device samsung-sm_g935v-0d75cc0d
D/ContextRelationManager: ContextRelationManager() : FEATURE_ENABLED=true
D/RelationGraph: garbageCollect()
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
I/InjectionManager: Inside getClassLibPath + mLibMap{0=, 1=}
D/ResourcesManager: For user 0 new overlays fetched Null
I/InjectionManager: Inside getClassLibPath caller 
W/System: ClassLoader referenced unknown path: /data/app/com.example.jamessingleton.chffrapi-2/lib/arm64
W/System: ClassLoader referenced unknown path: /data/app/com.example.jamessingleton.chffrapi-2/lib/arm64
I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
D/InjectionManager: InjectionManager
D/InjectionManager: fillFeatureStoreMap com.example.jamessingleton.chffrapi
I/InjectionManager: Constructor com.example.jamessingleton.chffrapi, Feature store :{}
I/InjectionManager: featureStore :{}
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
D/RelationGraph: garbageCollect()
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/Activity: performCreate Call Injection manager
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.WifivsDataDialog isFragment :true
D/SecWifiDisplayUtil: Metadata value : SecSettings2
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{173c66c V.E...... R.....I. 0,0-0,0}
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.MainActivity isFragment :false
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{8489435 I.E...... R.....ID 0,0-0,0}
I/Adreno: QUALCOMM build                   : c0299d7, I241dab1ec4
          Build Date                       : 01/25/16
          OpenGL ES Shader Compiler Version: XE031.06.00.05
          Local Branch                     : 
          Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.HB.1.1.1.06.00.01.063.117
          Remote Branch                    : NONE
          Reconstruct Branch               : NOTHING
D/libEGL: eglInitialize EGLDisplay = 0x7f950bf188
I/OpenGLRenderer: Initialized EGL, version 1.4
I/InjectionManager: dispatchCreateOptionsMenu :com.example.jamessingleton.chffrapi.MainActivity
I/InjectionManager: dispatchPrepareOptionsMenu :com.example.jamessingleton.chffrapi.MainActivity
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : com.example.jamessingleton.chffrapi
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@701efad time:68177067
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
I/WifiManager: isAllowWifiWarning() -> isCscWifiEnableWarning : false ChinaNalSecurityType : 
D/ViewRootImpl: #3 mView = null
E/ViewRootImpl: sendUserActionEvent() mView == null
D/ViewRootImpl: MSG_RESIZED: ci=Rect(0, 96 - 0, 1128) vi=Rect(0, 96 - 0, 1128) or=1
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
E/Network Testing: Available
I/Timeline: Timeline: Activity_launch_request id:com.example.jamessingleton.chffrapi time:68184023
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
D/RelationGraph: garbageCollect()
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
D/Activity: performCreate Call Injection manager
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.NavDrawerActivity isFragment :false
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{e6de345 I.E...... R.....ID 0,0-0,0}
D/SecWifiDisplayUtil: Metadata value : SecSettings2
I/InjectionManager: dispatchCreateOptionsMenu :com.example.jamessingleton.chffrapi.NavDrawerActivity
I/InjectionManager: dispatchPrepareOptionsMenu :com.example.jamessingleton.chffrapi.NavDrawerActivity
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
D/ViewRootImpl: MSG_RESIZED: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 1128) or=1
D/OpenGLRenderer: endAllActiveAnimators on 0x7f94044800 (RippleDrawable) with handle 0x7f9312a160
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@c8fad06 time:68184472
D/ViewRootImpl: MSG_RESIZED: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
E/ERROR: https://api.fullcontact.com/v2/person.json?email=&apiKey=USE_YOUR_OWN_API_KEY
         java.io.FileNotFoundException: https://api.fullcontact.com/v2/person.json?email=&apiKey=USE_YOUR_OWN_API_KEY
             at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:242)
             at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
             at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
             at com.example.jamessingleton.chffrapi.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:127)
             at com.example.jamessingleton.chffrapi.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:110)
             at android.os.AsyncTask.call(AsyncTask.java:295)
             at java.util.concurrent.FutureTask.run(FutureTask.java:237)
             at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:234)
             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
             at java.lang.Thread.run(Thread.java:818)
I/INFO: THERE WAS AN ERROR
V/ActivityThread: updateVisibility : ActivityRecord{579d47f token=android.os.BinderProxy@701efad {com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity}} show : false
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
I/zzai: Making Creator dynamically
W/ResourcesManager: getTopLevelResources: /data/app/com.google.android.gms-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.google.android.gms
D/ResourcesManager: For user 0 new overlays fetched Null
I/InjectionManager: Inside getClassLibPath caller 
D/ChimeraCfgMgr: Reading stored module config
W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/00000007/n/arm64-v8a
D/ChimeraFileApk: Primary ABI of requesting process is arm64-v8a
D/ChimeraFileApk: Classloading successful. Optimized code found.
I/Google Maps Android API: Google Play services client version: 9452000
I/Google Maps Android API: Google Play services package version: 9452440
I/c: Token loaded from file. Expires in: 430631730 ms.
I/c: Scheduling next attempt in 430331 seconds.
D/AbsListView: Get MotionRecognitionManager
E/MotionRecognitionManager: mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy@efb7e5f
E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@e0ff0ac
E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@e0ff0ac
W/System.err: mkdir failed: EEXIST (File exists) : /storage/emulated/0/Android/data/com.example.jamessingleton.chffrapi/cache/debug
W/System.err: mkdir failed: EEXIST (File exists) : /storage/emulated/0/Android/data/com.example.jamessingleton.chffrapi/cache
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/System.err: remove failed: ENOENT (No such file or directory) : /data/user/0/com.example.jamessingleton.chffrapi/files/event_store_v2_com.example.jamessingleton.chffrapi
I/InjectionManager: dispatchOnViewCreated > Target : com.google.android.gms.maps.MapFragment isFragment :true
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.ThirdFragment isFragment :true
I/Choreographer: Skipped 52 frames!  The application may be doing too much work on its main thread.
D/libEGL: eglInitialize EGLDisplay = 0x7f881eeea8
W/Google Maps Android API: GLHudOverlay deprecated; getDrawOrder(): no-op, return DrawOrder.HEADS_UP_DISPLAY
W/Google Maps Android API: GLHudOverlay deprecated; getDrawOrder(): no-op, return DrawOrder.HEADS_UP_DISPLAY
W/Google Maps Android API: GLHudOverlay deprecated; getDrawOrder(): no-op, return DrawOrder.HEADS_UP_DISPLAY
W/Google Maps Android API: GLHudOverlay deprecated; getDrawOrder(): no-op, return DrawOrder.HEADS_UP_DISPLAY
W/Google Maps Android API: GLHudOverlay deprecated; getDrawOrder(): no-op, return DrawOrder.HEADS_UP_DISPLAY
W/Google Maps Android API: GLHudOverlay deprecated; getDrawOrder(): no-op, return DrawOrder.HEADS_UP_DISPLAY
W/Google Maps Android API: GLHudOverlay deprecated; draw(): no-op
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{d33f815 V.E...... R.....I. 0,0-0,0}
W/Google Maps Android API: GLHudOverlay deprecated; draw(): no-op
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.jamessingleton.chffrapi, PID: 9120
                  java.lang.IllegalArgumentException: invalid provider: null
                      at android.location.LocationManager.checkProvider(LocationManager.java:1761)
                      at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1232)
                      at com.example.jamessingleton.chffrapi.ThirdFragment.onMapReady(ThirdFragment.java:95)
                      at com.google.android.gms.maps.MapFragment$zza.zza(Unknown Source)
                      at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
                      at android.os.Binder.transact(Binder.java:387)
                      at xz.a(:com.google.android.gms.DynamiteModulesB:82)
                      at maps.ad.u.run(Unknown Source)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:158)
                      at android.app.ActivityThread.main(ActivityThread.java:7224)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
W/ResourcesManager: getTopLevelResources: /data/app/com.google.android.gms-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.google.android.gms
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:1
I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 1
D/ChimeraFileApk: Primary ABI of requesting process is arm64-v8a
D/ChimeraFileApk: Classloading successful. Optimized code found.
D/GoogleCertificates: com.google.android.gms.googlecertificates module is loaded
D/GoogleCertificatesImpl: Fetched 163 Google release certificates
D/GoogleCertificatesImpl: Fetched 318 Google certificates

将你的这段代码移到 else 部分(所以只有在你获得许可的情况下,这段代码才会 运行):

    Criteria criteria = new Criteria();
    LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    double lat =  location.getLatitude();
    double lng = location.getLongitude();
    LatLng coordinate = new LatLng(lat, lng);
    CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 13);
    mMap.animateCamera(yourLocation);