【问题标题】:How to implement onPause() and onResume?如何实现 onPause() 和 onResume?
【发布时间】:2019-05-04 21:53:50
【问题描述】:

当我离开我的应用程序时,我的计数器会重置。

我知道我需要使用onPauseonResume 函数。但是,我不知道如何在代码中编写它。

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button b1 = findViewById(R.id.b1);

        eggcounter = 100;
        final ImageButton ImgButton = findViewById(R.id.eggBtn);

        ImgButton.setOnClickListener(
                new View.OnClickListener() {

                    public void onClick(View view) {
                        eggcounter = eggcounter - 1;
                        updateEgg();

                        if (eggcounter < 80) {

                            ImgButton.setImageResource(R.drawable.egg_2);

                            if (eggcounter <60){
                                ImgButton.setImageResource(R.drawable.egg_3);

                                if (eggcounter <40) {
                                    ImgButton.setImageResource(R.drawable.egg_4);

【问题讨论】:

标签: java android


【解决方案1】:

如果您想保存您的应用程序状态,您可以使用 Shared Preferences。示例:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // You can call to onResume() or on Pause() in onCreate();
        onResume();
        onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // After receiving this call you will usually receive a following call 
        // to onStop() and return to your activity 's onResume()
    }

    @Override
    public void onPause() {
        super.onPause();
        // When you receive a call, your activity is going into the background 
        // (to onPause) but your activity can be killed to reclaim resources 
        // (if there are not enough resources to start the new activity)
    }

所以如果您想保存您的实例应用程序状态,您可以保存到 Shared Preferences、SQLite 等。在 onPause() 或 onStop() 中调用它并在 onResume() 中回收这些数据

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多