活动生命周期示例

时间:2015-01-14 12:34:26

标签: android android-activity lifecycle oncreate ondestroy

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

3 个答案:

答案 0 :(得分:2)

我创建了一个示例来帮助您了解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");
}

}

答案 1 :(得分:0)

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

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

例如:您正在使用智能手机相机的应用上导航,突然您接到了朋友的来电。自动应用程序调用{​​{1}}方法,并且(假设)你内部有类似onPause()的东西,迫使相机停止在后台工作。

为什么需要这样做?来优化电池和内存使用情况。你不知道应用程序是否会被杀死并迫使它关闭......所以这是一个很好的做法来实现它。

您在Android Developers

上有这些示例和解释

希望有所帮助。

答案 2 :(得分:0)

来自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);

    }
}