I have a service that does something.

But when he onCreate is called a second time and the service stops doing his work.

To eliminate this - I need to save some data in SharedPreferences and for this I need to be sure that now is not the first launch of onCreate , but I don’t know how to do it.

Thanks in advance for your help.

    2 answers 2

    Suspend service execution on OnResume (). Well, or write data to SharedPreferences and delete them from there when you exit the application. The class itself with preferences:

     public class UserPreferences { private SharedPreferences sharedPreferences; private static UserPreferences userPreferences; public static UserPreferences getInstance(Context context) { if (userPreferences == null) { userPreferences = new UserPreferences(context); } return userPreferences; } private UserPreferences(Context context){ sharedPreferences = context.getSharedPreferences("sharedSettings",Context.MODE_PRIVATE); } public void storeUserInfo(String userCity){ SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("storeUserInfo", userCity); editor.commit(); } public String getUserInfo(){ return sharedPreferences.getString("storeUserInfo", null); } public void clearShared(){ SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.commit(); } 

    }

    Call this:

     UserPreferences userPreferences = userPreferences.getInstance(getActivity()); userPreferences.getInstance(getActivity()).storeUserInfo("SomeInfo"). 

    If you do not want to use the string in the preferences, then you can use the putInt () method. Further, it all depends on the wishes. In more detail about the life cycle of the application.

    • Thanks for the help. But I do not need a preference (I have already figured out with him, by the way, you can not complicate your life by highlighting a whole class) I need to find out what the launch of onCreate is now. First or second. That's all. I googled this question and did not find the answer so I wrote here. - Vlad Kramarenko
    • Running OnCreate () is always one, it can be called from different application states. Read more about application lifecycle management. Link attached to the answer - Ivan Vovk
    • You tell it to my service, which has two of them: the first when you press the Start button, and the second when you close the activation. - Vlad Kramarenko

    Get a static boolean variable in the service. In onCreate, check its value. If it is false, this is the first run. In other words, the following. After checking, set it to true