【问题标题】:Activity lifecycle example活动生命周期示例
【发布时间】:2015-01-14 12:34:26
【问题描述】:

我已经阅读了大量教程并看到了一堆示例,但我很难理解活动的生命周期。我明白会发生什么,我的问题是我似乎无法确切地弄清楚它应该如何编码。例如,假设我有一个简单的应用程序,一旦按下按钮就会添加两个数字。我知道要为 onCreate 方法编写什么代码,但我不知道要添加什么 onPause、onRestart 等。我只是删除变量的内容吗?任何帮助将不胜感激。

【问题讨论】:

  • 这完全取决于您的用例。

标签: android android-activity lifecycle oncreate ondestroy


【解决方案1】:

我创建了一个示例来帮助您了解 Activity 的生命周期。第一次启动屏幕时,会调用以下三个生命周期方法:

onCreate()
onStart()
onResume()

每当我们在应用程序运行时按下返回按钮时,都会调用以下生命周期方法:

onPause()
onStop()
onDestroy()

当我们在应用程序运行时按下主页按钮时,会调用以下生命周期方法:

onPause()
onStop()

当我们在按下主页按钮后恢复应用程序时,会调用以下生命周期方法:

onRestart()
onStart()
onResume()

我想这会对你有所帮助。

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toast.makeText(this, "Activity is created", Toast.LENGTH_SHORT).show();
    Log.i("onCreate():","Activity is created");
}

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    Toast.makeText(this, "Activity is started", Toast.LENGTH_SHORT).show();
    Log.i("onStart():","Activity started");
}

@Override
protected void onRestart() {
    // TODO Auto-generated method stub
    super.onRestart();
    Toast.makeText(this, "Activity is Restarted", Toast.LENGTH_SHORT).show();
    Log.i("onRestart():","Activity Restarted");
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    Toast.makeText(this, "Activity is Resumed", Toast.LENGTH_SHORT).show();
    Log.i("onResume():","Activity Resumed");
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    Toast.makeText(this, "Activity is Paused", Toast.LENGTH_SHORT).show();
    Log.i("onPause():","Activity paused");
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    Toast.makeText(this, "Activity is Stopped", Toast.LENGTH_SHORT).show();
    Log.i("onStop():","Activity stopped");
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Toast.makeText(this, "Activity is Destroyed", Toast.LENGTH_SHORT).show();
    Log.i("onDestroy():","Activity destroyed");
}

}

【讨论】:

  • 一个activity永远不会被untiadb shell销毁
  • 这很有帮助。非常感谢。
  • 当一个活动正在运行时,如果你按下返回按钮,那么该活动的 onDestroy() 方法就会被调用。
  • 如果您认为此答案有用,请点赞。
【解决方案2】:

在像你这样的单个应用程序上,建议您不需要覆盖任何这些方法......除非您想在任何活动转换之前/之后或应用程序关闭/打开/进入后台时执行重要操作,例如停止服务,启动会话,甚至在应用运行时记录活动状态。

了解所有活动生命周期回调以及如何使用它来优化应用非常重要。

例如:您正在使用智能手机摄像头的应用程序导航,突然接到朋友的电话。应用程序会自动调用onPause() 方法,并且(假设)在你内部有类似myCamera.release() 的东西,它会强制相机停止在后台工作。

为什么需要这样做?以优化电池和内存使用。您不知道该应用程序是否会被杀死并强制其关闭......所以实现它是一个好习惯。

你在Android Developers上有这个例子和解释

希望对您有所帮助。

【讨论】:

  • 这绝对是有帮助的。非常感谢。
【解决方案3】:

这个来自 coursera 实验室的代码检查一下

 package course.labs.activitylab;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ActivityOne extends Activity {

    // Use these as keys when you're saving state between reconfigurations
    private static final String RESTART_KEY = "restart";
    private static final String RESUME_KEY = "resume";
    private static final String START_KEY = "start";
    private static final String CREATE_KEY = "create";

    // String for LogCat documentation
    private final static String TAG = "Lab-ActivityOne";

    // Lifecycle counters

    // TODO:
    // Create variables named
    // mCreate, mRestart, mStart and mResume
    // to count calls to onCreate(), onRestart(), onStart() and
    // onResume(). These variables should not be defined as static.
    int mCreate = 0 , mRestart=0 , mStart = 0 , mResume = 0;

    // You will need to increment these variables' values when their
    // corresponding lifecycle methods get called.

    // TODO: Create variables for each of the TextViews
    // named mTvCreate, mTvRestart, mTvStart, mTvResume.
    // for displaying the current count of each counter variable

    TextView mTvCreate , mTvRestart , mTvStart , mTvResume ;

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

        // TODO: Assign the appropriate TextViews to the TextView variables
        // Hint: Access the TextView by calling Activity's findViewById()
        // textView1 = (TextView) findViewById(R.id.textView1);

        mTvCreate = (TextView) findViewById(R.id.create);
        mTvRestart = (TextView) findViewById(R.id.restart);
        mTvStart = (TextView) findViewById(R.id.start);
        mTvResume = (TextView) findViewById(R.id.resume);


        Button launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo);
        launchActivityTwoButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO:
                // Launch Activity Two
                // Hint: use Context's startActivity() method

                // Create an intent stating which Activity you would like to
                // start
                startActivity(new Intent (ActivityOne.this , ActivityTwo.class));

                // Launch the Activity using the intent

            }
        });

        // Has previous state been saved?
        if (savedInstanceState != null) {

            // TODO:
            // Restore value of counters from saved state
            // Only need 4 lines of code, one for every count variable

            mCreate = savedInstanceState.getInt(CREATE_KEY);
            mStart = savedInstanceState.getInt(START_KEY);
            mRestart = savedInstanceState.getInt(RESTART_KEY);
            mResume = savedInstanceState.getInt(RESUME_KEY);

        }

        // Emit LogCat message
        Log.i(TAG, "Entered the onCreate() method");

        // TODO:
        // Update the appropriate count variable
        // Update the user interface via the displayCounts() method
        mCreate ++;
        displayCounts();

    }

    // Lifecycle callback overrides

    @Override
    public void onStart() {
        super.onStart();

        // Emit LogCat message
        Log.i(TAG, "Entered the onStart() method");

        // TODO:
        // Update the appropriate count variable
        // Update the user interface
        mStart++;
        displayCounts();


    }

    @Override
    public void onResume() {
        super.onResume();

        // Emit LogCat message
        Log.i(TAG, "Entered the onResume() method");

        // TODO:
        // Update the appropriate count variable
        // Update the user interface
        mResume ++;
        displayCounts();

    }

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

        // Emit LogCat message
        Log.i(TAG, "Entered the onPause() method");

    }

    @Override
    public void onStop() {
        super.onStop();

        // Emit LogCat message
        Log.i(TAG, "Entered the onStop() method");
    }

    @Override
    public void onRestart() {
        super.onRestart();

        // Emit LogCat message
        Log.i(TAG, "Entered the onRestart() method");

        // TODO:
        // Update the appropriate count variable
        // Update the user interface
        mRestart ++;
        displayCounts();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        // Emit LogCat message
        Log.i(TAG, "Entered the onDestroy() method");
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // TODO:
        // Save state information with a collection of key-value pairs
        // 4 lines of code, one for every count variable
        savedInstanceState.putInt(CREATE_KEY, mCreate);
        savedInstanceState.putInt(START_KEY, mStart);
        savedInstanceState.putInt(RESTART_KEY, mRestart);
        savedInstanceState.putInt(RESUME_KEY, mResume);



    }

    // Updates the displayed counters
    // This method expects that the counters and TextView variables use the
    // names
    // specified above
    public void displayCounts() {

        // TODO - uncomment these lines

        mTvCreate.setText("onCreate() calls: " + mCreate);
        mTvStart.setText("onStart() calls: " + mStart);
        mTvResume.setText("onResume() calls: " + mResume);
        mTvRestart.setText("onRestart() calls: " + mRestart);

    }
}

【讨论】:

    猜你喜欢
    • 2014-05-18
    • 1970-01-01
    • 2013-01-13
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 2014-09-26
    • 1970-01-01
    相关资源
    最近更新 更多