Android activity life cycle - what are all these methods for?

前端 未结 8 2068
轮回少年
轮回少年 2020-11-21 06:18

What is the life cycle of an Android activity? Why are so many similar sounding methods (onCreate(), onStart(), onResume()) called dur

8条回答
  •  面向向阳花
    2020-11-21 07:05

    Adding some more info on top of highly rated answer (Added additional section of KILLABLE and next set of methods, which are going to be called in the life cycle):

    Source: developer.android.com

    Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.

    Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created.

    Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

    I would like to add few more methods. These are not listed as life cycle methods but they will be called during life cycle depending on some conditions. Depending on your requirement, you may have to implement these methods in your application for proper handling of state.

    onPostCreate(Bundle savedInstanceState)
    

    Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called).

    onPostResume()
    

    Called when activity resume is complete (after onResume() has been called).

    onSaveInstanceState(Bundle outState)
    

    Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

    onRestoreInstanceState(Bundle savedInstanceState)
    

    This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState.

    My application code using all these methods:

    public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    
        private EditText txtUserName;
        private EditText txtPassword;
        Button  loginButton;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Log.d("Ravi","Main OnCreate");
            txtUserName=(EditText) findViewById(R.id.username);
            txtPassword=(EditText) findViewById(R.id.password);
            loginButton =  (Button)  findViewById(R.id.login);
            loginButton.setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View view) {
            Log.d("Ravi", "Login processing initiated");
            Intent intent = new Intent(this,LoginActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("userName",txtUserName.getText().toString());
            bundle.putString("password",txtPassword.getText().toString());
            intent.putExtras(bundle);
            startActivityForResult(intent,1);
           // IntentFilter
        }
        public void onActivityResult(int requestCode, int resultCode, Intent resIntent){
            Log.d("Ravi back result:", "start");
            String result = resIntent.getStringExtra("result");
            Log.d("Ravi back result:", result);
            TextView txtView = (TextView)findViewById(R.id.txtView);
            txtView.setText(result);
    
            Intent sendIntent = new Intent();
            //sendIntent.setPackage("com.whatsapp");
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, "Message...");
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            Log.d("Ravi","Main Start");
        }
    
        @Override
        protected void onRestart() {
            super.onRestart();
            Log.d("Ravi","Main ReStart");
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            Log.d("Ravi","Main Pause");
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            Log.d("Ravi","Main Resume");
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            Log.d("Ravi","Main Stop");
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            Log.d("Ravi","Main OnDestroy");
        }
    
        @Override
        public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
            super.onPostCreate(savedInstanceState, persistentState);
            Log.d("Ravi","Main onPostCreate");
        }
    
        @Override
        protected void onPostResume() {
            super.onPostResume();
            Log.d("Ravi","Main PostResume");
        }
    
        @Override
        public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
            super.onSaveInstanceState(outState, outPersistentState);
        }
    
        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
        }
    }
    

    Login Activity:

    public class LoginActivity extends AppCompatActivity {
    
        private TextView txtView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            txtView = (TextView) findViewById(R.id.Result);
            Log.d("Ravi","Login OnCreate");
            Bundle bundle = getIntent().getExtras();
            txtView.setText(bundle.getString("userName")+":"+bundle.getString("password"));
            //Intent  intent = new Intent(this,MainActivity.class);
            Intent  intent = new Intent();
            intent.putExtra("result","Success");
            setResult(1,intent);
           // finish();
        }
    }
    

    output: ( Before pause)

    D/Ravi: Main OnCreate
    D/Ravi: Main Start
    D/Ravi: Main Resume
    D/Ravi: Main PostResume
    

    output: ( After resume from pause)

    D/Ravi: Main ReStart
    D/Ravi: Main Start
    D/Ravi: Main Resume
    D/Ravi: Main PostResume
    

    Note that onPostResume() is invoked even though it's not quoted as life cycle method.

提交回复
热议问题