App crashes while calling LocationUpdatesService with permission with NullPointerException

前端 未结 2 1252
眼角桃花
眼角桃花 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;
            }
        };
    
    0 讨论(0)
  • 2020-12-22 01:37

    Update code to this code mService is null because you are initilaizing it after mService.requestLocationUpdates();

     @Override
                protected void onStart() {
                    super.onStart();
                    PreferenceManager.getDefaultSharedPreferences(this)
                            .registerOnSharedPreferenceChangeListener(this);
            
                    if (!checkPermissions()) {
                        requestPermissions();
                    } else {
     bindService(new Intent(this, LocationUpdatesService.class), mServiceConnection,
                            Context.BIND_AUTO_CREATE);
                        mService.requestLocationUpdates(); //CRASHING HERE
                    }
                    // 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.
                   
                }
            
    
    0 讨论(0)
提交回复
热议问题