Android核心技術-day06-05-Activity生命週期,應用場景
阿新 • • 發佈:2018-11-07
package com.gaozewen.lifecycle; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; public class MainActivity extends AppCompatActivity { // 當介面被建立時被呼叫 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println("onCreate"); } // 應用程式介面,使用者可見時呼叫 @Override protected void onStart() { super.onStart(); System.out.println("onStart"); } // 應用程式介面 獲得焦點時呼叫 // 例:有遮罩層遮住了,重新回來獲得焦點時呼叫 @Override protected void onResume() { super.onResume(); System.out.println("onResume"); } // 當介面再次可見時呼叫 @Override protected void onRestart() { super.onRestart(); System.out.println("onRestart"); } // 當介面失去焦點時呼叫 @Override protected void onPause() { super.onPause(); System.out.println("onPause"); } // 當介面不可見時呼叫 @Override protected void onStop() { super.onStop(); System.out.println("onStop"); } // 當介面被銷燬時呼叫 @Override protected void onDestroy() { super.onDestroy(); System.out.println("onDestroy"); } public void click(View view) { Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); } }
應用場景
package com.gaozewen.lifecycletest; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private SharedPreferences sp; private EditText mEt_content; private TextView mTv_blood; private int blood = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // sp = getSharedPreferences("config", MODE_PRIVATE); // mEt_content = (EditText) findViewById(R.id.et_content); // mEt_content.setText(sp.getString("content","")); setContentView(R.layout.activity_game); mTv_blood = (TextView) findViewById(R.id.tv_blood); } public void click(View view) { // manifest.xml android:configChanges="orientation|keyboardHidden|screenSize" // 當上述事件發生,血量不會恢復 blood -= 7; if (blood>0) { mTv_blood.setText("剩餘生命值:"+blood); } else { mTv_blood.setText("已經被 KO 啦!"); } } @Override protected void onStart() { super.onStart(); System.out.println("繼續播放視訊..."); } @Override protected void onStop() { super.onStop(); System.out.println("暫停播放視訊,記錄當前播放的位置"); } @Override protected void onDestroy() { super.onDestroy(); // String content = mEt_content.getText().toString().trim(); // SharedPreferences.Editor edit = sp.edit(); // edit.putString("content",content); // edit.apply(); } }