There is an example of how to start searching and sending coordinates every five minutes using an alarm clock, but if you close the application with the back key, sending will stop pretty quickly, because an error will occur in the class LocationTracker.java

because:

 Location currentLocation = LocationProvider.getInstance().getCurrentLocation(); 

Will give null .

I think this happens because in SinglePhone LocationProvider.java Context is lost after the application is closed. After the error, the singleton tries to work with another Context , but the interaction does not work because the Context is different.

I'm right?

How to save the Context in SharedPreferences to get it and substitute it into a singleton when the application with the context is closed?

  • one
    You just need to use the Service. - Android Android
  • And if without Service? - Gennady
  • Why not? Is this fundamentally your task? Or have you never worked with him or want to come up with another crutch? - Android Android
  • If everything starts on the alarm clock, then I don’t want the service to be still hanging. - Gennady
  • And why do not you like the option with the service that just makes sleep() for 5 minutes to your thread? - anber

2 answers 2

How to save Context in SharedPreferences to get it and substitute it into singelton when the application with the context is closed?

No It contains information about the current state of the environment, and even if you could write it down somewhere or when it was restored, it is obsolete.

About why this code stops working - ask the author of the answer to which you refer, he wrote a rather large wrapper there, and I do not want to dig into it.

    I suppose you need in BroadcastReceiver (an example from a link) this:

     Location currentLocation = LocationProvider.getInstance().getCurrentLocation(); 

    replaced by :

     LocationProvider locationProvider = LocationProvider.getInstance(); locationProvider.configureIfNeeded(сontext); Location currentLocation = locationProvider.getCurrentLocation(); 

    And you receive null as in an example

     private static Location currentLocation; 

    not initialized.

    • Unfortunately it does not help, the context after the error changes and the currentLocation gets null. - Gennady
    • The context changes and the class instance is re-created, it has an empty field, it does not have time to update !!! You make an update request, but for now the request does not have time to work out. You immediately request a location, and that's null. The context has nothing to do with, I can advise you to spend the time and still figure out where the coordinates come from, how the context relates and what the Context is. - Vitalii Obideiko