开发者

How do I make my entire app run in the background?

I made an app that is just a simple counter that will keep track of a u开发者_运维百科ser's strokes as they play golf and save their score while doing it. I simply want the app to not be killed when the user exits out. I just want it to run in the background. So the user can re-enter the program after doing other things, (like texting or checking email)

I understand I need to use services but while trying to research the topic on the web and in other forums, it seems that they all explain how to have a specific activity in the app to continue, not the entire app.

How might I do this?


You could do something like this

  @Override
  protected void onPause()
  {
    super.onPause();

    SharedPreferences settings = getSharedPreferences("YourOwnPickedName", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("score", the_users_score);
  }

and get the score back by doing

  @Override
  protected void onResume()
  {
    super.onResume();
    SharedPreferences settings = getSharedPreferences("YourOwnPickedName", 0);
    the_users_score = settings.getString("score", "0");
  }


You should just store data to permanent storage instead of trying to keep the app alive indefinitely (which can not be 100% achieved anyway):

http://developer.android.com/guide/topics/data/data-storage.html


I would like to point out that Ben Williams was mostly correct, but he missed a step (editor.commit();) in the save file. The data does not get stored in the settings file until it is committed:

@Override
protected void onPause()
  {
     super.onPause();

     SharedPreferences settings = getSharedPreferences("YourOwnPickedName", 0);
     SharedPreferences.Editor editor = settings.edit();
     editor.putString("score", the_users_score);
     editor.commit();
  }

I suggest looking at http://developer.android.com/reference/android/app/Activity.html to see the lifecycle (to know exactly where you want to put it for what situation).


You can make it as a windows service application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜