Search code examples
javaandroidservicelocationbackground-service

Service already running while it shouldnt in Location Using Background Service code


I am having an app that has to get the location of where I am in many activities. I found this very helpful complete piece of code here. Its how to Get Current Location Using Background Service. I implemented it in my code. The first time it worked ok. The next, when it reached this if

if (mPref.getString("service", "").matches("")) {
        medit.putString("service", "service").commit();
        Intent intent = new Intent(getApplicationContext(), GoogleService.class);
        startService(intent);

 } else {
        Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
  }

I get the message that service is already running. Why this happens? I have closed and reopened the app, why the service still running? Help pls, its very important, thank you


Solution

  • If you use SharedPreferences to persist the info about your Service then the info survives the app restart and so your if condition is always false (when you do mPref.commit() you save the key pair to the file).