App crashes while calling LocationUpdatesService with permission with NullPointerException

前端 未结 2 1277
眼角桃花
眼角桃花 2020-12-22 01:15

I\' trying to implement Google\'s android foreground location sample from github in my application. It works fine in the first run of the application. It requests for locati

2条回答
  •  青春惊慌失措
    2020-12-22 01:24

    I am not sure, but try this:

    @Override
        protected void onStart() {
            super.onStart();
            PreferenceManager.getDefaultSharedPreferences(this)
                    .registerOnSharedPreferenceChangeListener(this);
    
            if (!checkPermissions()) {
                requestPermissions();
            } else if (mService != null) { // add null checker
                mService.requestLocationUpdates();
            }
            // Bind to the service. If the service is in foreground mode, this signals to the service
            // that since this activity is in the foreground, the service can exit foreground mode.
            bindService(new Intent(this, LocationUpdatesService.class), mServiceConnection,
                    Context.BIND_AUTO_CREATE);
        }
    

    Also:

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                LocationUpdatesService.LocalBinder binder = (LocationUpdatesService.LocalBinder) service;
                mService = binder.getService();
                mService.requestLocationUpdates(); // also request it here
                mBound = true;
            }
    
            @Override
            public void onServiceDisconnected(ComponentName name) {
                mService = null;
                mBound = false;
            }
        };
    

提交回复
热议问题