开发者

Locking screen in Android speeds up game

I'm updating my game using a Handler posting a delayed Runnable.

public class Example implements Runnable
{
  Handler handler;
  public Example()
  {
    handler = new Handler();
    handler.postDelayed(this,10);
  }
  public vo开发者_Go百科id run()
  {
    handler.postDelayed(this,10);
  }
}

Whenever I press the lock screen button and then resume the game, it runs much faster than it is supposed to. Every time I lock the screen and resume, it runs faster and faster. However, if I restart the activity or finish and then re-open the activity, it runs at normal speed again. Help please. Thanks in advance.


What seems to be happening is every time you lock your screen and then resume it is making another Runnable on top of the Runnable you already have doubling your run thus making the thread go faster and faster everytime, you need to somehow pause your thread something like thread.sleep() or something similar when you lock your screen so when you resume you aren't recreating a new Runnable and instead just starting from where you left off in your thread.

If you are making a new Runnable in an onCreate method. It is going to get called anytime the phone is rotated, or when the phone resumes etc. and thus is why you are probably having this issue. The reason it doesn't happen after you finish() your activity or close your app is because when you restart the app, that Runnable is going to get created once, until you start locking the phone and resuming again etc.

you may also want to look at an inner class you can use to help handle your threads:

public class YourClass extends Activity {

    public void yourUpdateMethod() {
        runOnUiThread(new Runnable() {
            public void run() {
                new YourUpdateClass().execute(0, null, null);
            }
        });
    }

    private class YourUpdateClass extends AsyncTask<Integer, Void, Void> {


            @Override
            protected synchronized Void doInBackground(Integer... index) {
                return null;
            }

            @Override
            protected synchronized void onPostExecute(Void result) {
                //your statements here
            }
    }
}

This might help handle threads that have to be paused/restarted/resumed or whatever a little better. More info here: http://developer.android.com/reference/android/os/AsyncTask.html

Dunno how it would work in a game though, didn't play around with that.

Good Luck, hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜