Lập trình Android tiếng Việt - Chapter 3: Android Application's Life Cycle


Một activity thường trình diễn một giao diện người dùng đơn bằng hình ảnh mà từ đó có thể thực hiện một số hành động (action).

 

Tuy các activity cộng tác với nhau để hợp thành một giao diện người dùng thống nhất, mỗi activity có tính độc lập với các activity khác.


Thông thường, một activity được đánh dấu làm activity đầu tiên – cái sẽ được trình diễn cho người dùng khi ứng dụng được bật lên.

 

Việc gọi một activity từ bên trong một activity khác được thực hiện qua việc activity hiện hành gọi activity tiếp theo qua cơ chế intent. (startActivity(Intent))

 

pptx47 trang | Chuyên mục: Android | Chia sẻ: dkS00TYs | Lượt xem: 1954 | Lượt tải: 1download
Tóm tắt nội dung Lập trình Android tiếng Việt - Chapter 3: Android Application's Life Cycle, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
mo. Part 2 private LinearLayout myScreen; private TextView txtToDo; private EditText txtColorSelect; private Button btnFinish; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myScreen = (LinearLayout) findViewById(R.id.myScreen); txtToDo = (TextView) findViewById(R.id.txtToDo); String msg = "Instructions: \n " + "0. New instance (onCreate, onStart, onResume) \n " + "1. Back Arrow (onPause, onStop, onDestroy) \n " + "2. Finish (onPause, onStop, onDestroy) \n " + "3. Home (onPause, onStop) \n " + "4. After 3 > App Tab > re-execute current app \n " + " (onRestart, onStart, onResume) \n " + "5. Run DDMS > Receive a phone call or SMS \n " + " (onRestart, onStart, onResume) \n " + "6. Enter some data - repeat steps 1-5 \n "; txtToDo.setText(msg); Code: Life Cycle Demo. Part 3 txtColorSelect = (EditText) findViewById(R.id.txtColorSelect); // you may want to skip discussing the listener until later txtColorSelect.addTextChangedListener(new TextWatcher(){ public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } public void beforeTextChanged(CharSequence s, int start, int count,int after) { // TODO Auto-generated method stub } public void afterTextChanged(Editable s) { changeBackgroundColor(s.toString()); } }); btnFinish = (Button) findViewById(R.id.btnFinish); btnFinish.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { finish(); } }); Toast.makeText(getApplicationContext(), "onCreate", 1).show(); } 33 3. Android – Application's Life Cycle Example: Life Cycle 33 34 3. Android – Application's Life Cycle Example: Life Cycle 34 Code: Life Cycle Demo. Part 4 @Override protected void onPause() { super.onPause(); saveDataFromCurrentState(); Toast.makeText(this, "onPause", 1).show(); } @Override protected void onRestart() { super.onRestart(); Toast.makeText(this, "onRestart", 1).show(); } @Override protected void onResume() { super.onResume(); Toast.makeText(this, "onResume", 1).show(); } 35 3. Android – Application's Life Cycle Example: Life Cycle 35 Code: Life Cycle Demo. Part 5 @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); updateFromSavedState(); Toast.makeText(this, "onStart", 1).show(); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Toast.makeText(this, "onDestroy", 1).show(); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); Toast.makeText(this, "onStop", 1).show(); } 36 3. Android – Application's Life Cycle Example: Life Cycle 36 Code: Life Cycle Demo. Part 6 protected void saveDataFromCurrentState() { SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode); SharedPreferences.Editor myEditor = myPrefs.edit(); myEditor.putString("myBkColor", txtColorSelect.getText().toString()); myEditor.commit(); } // saveDataFromCurrentState protected void updateFromSavedState() { SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode); if ((myPrefs != null) && (myPrefs.contains("myBkColor"))) { String theChosenColor = myPrefs.getString("myBkColor",""); txtColorSelect.setText(theChosenColor); changeBackgroundColor(theChosenColor); } } // updateFromSavedState protected void clearMyPreferences() { SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode); SharedPreferences.Editor myEditor = myPrefs.edit(); myEditor.clear(); myEditor.commit(); } // clearMyPreferences 37 3. Android – Application's Life Cycle Example: Life Cycle 37 Code: Life Cycle Demo. Part 7 private static String MYPREFSID; //used in part 6 private static int actMode; //used in part 6 private void changeBackgroundColor (String theChosenColor){ // change background color if (theChosenColor.contains("red")) myScreen.setBackgroundColor(0xffff0000); else if (theChosenColor.contains("green")) myScreen.setBackgroundColor(0xff00ff00); else if (theChosenColor.contains("blue")) myScreen.setBackgroundColor(0xff0000ff); else { //reseting user preferences clearMyPreferences(); myScreen.setBackgroundColor(0xff000000); } } 	 38 3. Android – Application's Life Cycle Example: Life Cycle 38 Code: Life Cycle Demo. Part 8 /* protected void onRestoreInstanceState(Bundle savedInstanceState) 	 This method is called after onStart() when the activity is being re-initialized from a previously saved state. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle). Phương thức này được gọi sau onStart() khi activity đang được khởi tạo lại từ  trạng thái đã lưu lại trước đó. Cài đặt mặc định của phương thức này khôi phục  trạng thái view đã được lưu bởi onSaveInstanceState(Bundle). */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); Toast.makeText(getBaseContext(), "onRestoreInstanceState ...BUNDLING", Toast.LENGTH_LONG).show(); } 39 3. Android – Application's Life Cycle Example: Life Cycle 39 Code: Life Cycle Demo. Part 9 /* protected void 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). This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via: onCreate(Bundle) or onRestoreInstanceState(Bundle). Phương thức này được gọi trước khi một activity có thể bị kill sao cho khi nó quay lại nó có thể phục hồi trạng thái của mình. Ví dụ, khi activity A bị hệ thống kill để lấy tài nguyên, A sẽ có cơ hội lưu trạng thái hiện hành của giao diện người dùng bằng phương thức này, để khi người dùng quay lại activity A, trạng thái của giao diện người dùng có thể được khôi phục qua các phương thức onCreate(Bundle) hoặc onRestoreInstanceState(Bundle). (Đối tượng Bundle mà phương thức này xây dựng sẽ được truyền cho cả hai phương thức khôi phục đó) */	 40 3. Android – Application's Life Cycle Example: Life Cycle 40 Code: Life Cycle Demo. Part 10 @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Toast.makeText(getBaseContext(), "onSaveInstanceState ...BUNDLING", Toast.LENGTH_LONG).show(); } // onSaveInstanceState }//LifeCycleDemo 41 3. Android – Application's Life Cycle Example: Life Cycle 41 onCreate… onStart… onResume… 42 3. Android – Application's Life Cycle Example: Life Cycle 42 onPause… onStop… onDestroy… After pressing “Back Arrow” Application’s Life Cycle 43 Questions ? Application’s Life Cycle 44 Appendix Lưu các thông tin trạng thái khác @Override public void onCreate(Bundle savedInstanceState) { 	... somevalue = savedInstanceState.getString(SOME_KEY); 	... } ... @Override protected void onSaveInstanceState(Bundle outState) { 	super.onSaveInstanceState(outState); 	outState.putString(SOME_KEY, "blah blah blah"); } 45 45 3. Android – Application's Life Cycle Homework Your turn! EXPERIMENT 1. Viết một ứng dụng Android. (“PuraVida”) để thử nghiệm các vòng đời khác nhau của ứng dụng. Layout tại main.xml cần có một Button (text: “Finish”, id: btnFinish) và một EditText container (txt: “” , id: txtMsg). Dùng phương thức onCreate để nối button và textbox với chương trình. Thêm dòng mã sau: Toast.makeText(this, "onCreate", 1).show(); Phương thức click chỉ có một lệnh: finish(); dùng để kết thúc ứng dụng. Thêm một lệnh Toast (tương tự như trên) cho từng event trong 6 event còn lại. Để đơn giản, hãy dùng menu Source > Override/Implement Methods… của Eclipse Tại cửa sổ option, đánh dấu các event sau: onStart, onResume, onPause, onStop, onDestroy, onRestart 	(để ý xem có bao nhiêu phương thức onEvent… tại đó!!!) 6.Lưu chương trình. Teaching notes 46 46 3. Android – Application's Life Cycle Homework Your turn! EXPERIMENT 1 (cont.) Dịch và chạy ứng dụng. Ghi lại chuỗi các message hiển thị bởi các lệnh Toast. Nhấn nút FINISH. Quan sát chuỗi các trạng thái. Chạy lại ứng dụng Nhấn nút HOME của emulator. Chuyện gì xảy ra? Click vào launch pad, tìm icon và quay lại ứng dụng “PuraVida”. Chuỗi message nào được hiển thị? Click phím CALL của emulator. Ứng dụng ở trạng thái paused hay stopped? Click phím BACK để quay lại ứng dụng. Long-tap vào nút HANG-UP. Chuyện gì xảy ra? Teaching notes 47 47 3. Android – Application's Life Cycle Homework Your turn! EXPERIMENT 2 Chạy emulator thứ hai. Thực hiện một voice-call tới emulator thứ nhất hiện vẫn hiển thị ứng dụng của bạn. Chuyện gì xảy ra? (yêu cầu đồng bộ thời gian thực) Gửi một text-message tới emulator thứ nhất (yêu cầu không đồng bộ - asynchronous attention request) Viết một câu vào EditText box (“these are the best moments of my life….”). Chạy lại ứng dụng. Chuyện gì xảy ra đối với dòng text? Teaching notes 48 48 3. Android – Application's Life Cycle Homework Your turn! EXPERIMENT 3 Đảm bảo tính bền vững của dữ liệu (data persistency). Thêm vào phương thức onPause đoạn sau 	SharedPreferences myFile1 = getSharedPreferences("myFile1", 	 Activity.MODE_PRIVATE); 	SharedPreferences.Editor myEditor = myFile1.edit(); 	String temp = txtMsg.getText().toString(); 	myEditor.putString("mydata", temp); 	myEditor.commit(); Thêm vào phương thức onResume đoạn sau SharedPreferences myFile = getSharedPreferences("myFile1", 	 Activity.MODE_PRIVATE); if ( (myFile != null) && (myFile.contains("mydata")) ) { 	String temp = myFile.getString("mydata", "***"); 	txtMsg.setText(temp); } Giờ thì chuyện gì xảy ra với dữ liệu đã nhập vào text box? Teaching notes 

File đính kèm:

  • pptxLập trình Android tiếng Việt - Chapter 3 Android Application's Life Cycle.pptx
Tài liệu liên quan