简体   繁体   中英

FPS reduction when resuming the activity

I tried making my first android app. It works well but strangely when I pause then resume the main activity (basically when showing the settings menu) the application FPS decrease a lot, and I've no clue why.

Here is my structure:
DrawView is a class implementing the View class with an "update" method which does the stuff at each frame (calculating and drawing).
The main activity create a DrawView (as content view) and with a Handler and a Runnable requests it to refresh every 10ms.

Here is the (simplified) code of Main.java:

public class Main extends Activity {
    DrawView drawView;
    private Handler myHandler;
    private Runnable myRunnable = new Runnable() {
        public void run() {
            drawView.update();
            myHandler.postDelayed(this, 10);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        drawView = new DrawView(this);
        setContentView(drawView);
        myHandler = new Handler();
        myHandler.post(myRunnable);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(myHandler != null) myHandler.removeCallbacks(myRunnable);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(myHandler != null) myHandler.post(myRunnable);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId())
        {
        case R.id.menu_close:
            finish();
            break;
        case R.id.menu_settings:
            Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
            startActivity(settingsActivity);
        }
        return super.onOptionsItemSelected(item);
    }
}

By implementing a FPS counter in the DrawView.update method, I noticed that the FPS drop from 100+ at the begining to a ceiling of 60 after opening then closing the preferences Activity.

I don't understand where is my mistake.

The reason is simple: you post your Runnable object twice (in onCreate and onResume methods) and DrawView.update() actually will be called more often than once per 10 ms.

When Activity is paused you call myHandler.removeCallbacks(myRunnable) and it removes BOTH previously added objects. After Activity is resumed you post the Runnable again but only once (because 'onCreate' is not called).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM