Android chapter03-life-cycle

48
Android Application’s Life Cycle Notes are based on: Unlocking Android by Frank Ableson, Charlie Collins, and Robi Sen. ISBN 978-1-933988-67-2 Manning Publications, 2009. Android Developers http://developer.android.com/index.html Part 3

description

 

Transcript of Android chapter03-life-cycle

Page 1: Android chapter03-life-cycle

Android Application’s Life Cycle

Notes are based on: Unlocking Android by Frank Ableson, Charlie Collins, and Robi Sen. ISBN 978-1-933988-67-2Manning Publications, 2009.

Android Developers http://developer.android.com/index.html

Part 3

Page 2: Android chapter03-life-cycle

2

3. Android – Application's Life Cycle

Outline• Android Applications

• Activity, Service, Broadcast receiver, Content provider• process

• Application’s Life Cycle • Activity Stack• Life Cycle States • Life Cycle Events• Application’s Lifetime: Visible Lifetime Foreground Lifetime• Life Cycle Methods: onCreate(), onStart(), onDestroy()...• Example: LifeCycleDemo

2

Page 3: Android chapter03-life-cycle

3

3. Android – Application's Life Cycle

Android Applications

Một ứng dụng (application) bao gồm một hoặc vài component được định nghĩa trong manifest file của ứng dụng, gồm các loại:

1. Activity2. Service3. BroadcastReceiver 4. ContentProvider

Ứng dụng Android so với Java application:• Cũng viết 1 class để thực hiện một công việc nào đó• Không dùng hàm main khởi tạo một object thuộc class đó

và gọi phương thức của nó• Tùy theo loại object (Activity, Service....), Android sẽ gọi

constructor và quản lý vòng đời của object đó3

Page 4: Android chapter03-life-cycle

4

3. Android – Application's Life Cycle

Android Applications

1. Activity

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))

4

Page 5: Android chapter03-life-cycle

5

3. Android – Application's Life Cycle

Android Applications

2. Service

Một service không có giao diện người dùng bằng hình ảnh, thay vào đó, nó chạy ẩn tại background trong một khoảng thời gian không xác định.

Có thể kết nối (bind to) với một service đang chạy (hoặc chạy service đó nếu nó hiện chưa chạy).

Trong khi đang kết nối, ta có thể liên lạc với service đó qua một giao diện mà nó cung cấp.

5

Page 6: Android chapter03-life-cycle

6

3. Android – Application's Life Cycle

Android Applications

3. Broadcast receiver

Một broadcast receiver là một component không làm gì ngoài việc nhận và phản ứng với các broadcast announcement.

Nhiều broadcast bắt nguồn từ mã hệ thống (ví dụ “you got mail“), nhưng bất cứ ứng dụng nào cũng có thể phát broadcast.

Broadcast receiver không hiển thị giao diện người dùng. Tuy nhiên, chúng có thể bật một activity để đáp ứng thông tin mà chúng nhận được, hoặc - giống như cách làm của các service – chúng có thể dùng notification manager để thông báo cho người dùng.

6

Page 7: Android chapter03-life-cycle

7

3. Android – Application's Life Cycle

Android Applications

4. Content provider

Một content provider cung cấp một tập dữ liệu của một ứng dụng cho các ứng dụng khác.

Dữ liệu thường được lưu trong hệ thống file, hoặc trong một CSDL SQLite.

Mỗi content provider cài đặt một tập chuẩn các phương thức cho phép các ứng dụng khác lấy và lưu trữ dữ liệu thuộc loại mà nó kiểm soát.

Tuy nhiên, các ứng dụng không gọi trực tiếp các phương thức này. Thay vào đó, chúng dùng một đối tượng content resolver và gọi các phương thức của đối tượng đó. Một content resolver có thể nói chuyện với một content provider bất kì; nó cộng tác với provider để quản lý quá trình liên lạc xuyên tiến trình (interprocess communication) phát sinh.

7

Page 8: Android chapter03-life-cycle

8

3. Android – Application's Life Cycle

Android Applications

Mỗi ứng dụng Android chạy trong một tiến trình riêng(cùng với thực thể máy ảo Dalvik của riêng nó).

Mỗi khi có một request cần được xử lý bởi một component cụ thể nào đó, • Android đảm bảo rằng tiến trình ứng dụng của component đó đang

chạy, • khởi động nó nếu cần, và• đảm bảo rằng có sẵn một thực thể (instance) của component đó, nếu

cần thì tạo ra thực thể đó.

8

Page 9: Android chapter03-life-cycle

9

3. Android – Application's Life Cycle

Application’s Life Cycle

Một tiến trình Linux dành cho một ứng dụng Android được tạo ra cho ứng dụng đó khi có một số phần code của ứng dụng đó cần chạy. Tiến trình đó sẽ tồn tại cho đến khi

1. không còn cần đến nó nữa, HOẶC 2. hệ thống cần thu hồi bộ nhớ để cho các ứng dụng khác dùng.

9

Page 10: Android chapter03-life-cycle

10

3. Android – Application's Life Cycle

Application’s Life Cycle

Một tính chất đặc biệt nhưng căn bản của Android là các tiến trình không trực tiếp kiểm soát vòng đời của chính mình.

Thay vào đó, số phận của nó được hệ thống quyết định dựa trên thông tin về

1. Các phần ứng dụng hiện đang chạy, 2. Tầm quan trọng của chúng đối với người dùng3. Hệ thống còn bao nhiêu bộ nhớ.

10

Page 11: Android chapter03-life-cycle

11

3. Android – Application's Life Cycle

Component Lifecycles

11

Các component của ứng dụng có một vòng đời (lifecycle)

1. bắt đầu: khi Android tạo thực thể của component để đáp ứng các intent

2. kết thúc: khi các thực thể đó bị hủy.

3. giữa chừng: đôi khi chúng có thể active hoặc inactive, hay trong trường hợp của các activity- visible hoặc invisible đối với người dùng.

Life as an Android Application:Active / InactiveVisible / Invisible

Start End

Page 12: Android chapter03-life-cycle

12

3. Android – Application's Life Cycle

Activity Stack

12

• Các activity trong hệ thống được quản lý bằng một activity stack.

• Khi một activity mới được bật, nó được đặt trên đỉnh stack và trở thành running activity -- activity trước nó nằm bên dưới ở trong stack, và sẽ không hiện trở lại tại foreground (đỉnh stack) cho đến khi activity mới kết thúc.

• Nếu người dùng nhấn phím Back, activity tiếp theo trong stack sẽ dịch lên và chuyển sang trạng thái hoạt động (active).

Page 13: Android chapter03-life-cycle

13

3. Android – Application's Life Cycle

Activity Stack

13

New Activity

Activity 1

Activity 2

Activity 3

Last Running Activity

Activity n-1

. . .

Running Activity

New Activity started

Back button pushed or running activity closed

Activity StackPrevious Activities Removed to

free resources

Figure 1.

Page 14: Android chapter03-life-cycle

14

3. Android – Application's Life Cycle

Life Cycle States

14

An activity has essentially three states:

1. It is active or running2. It is paused or3. It is stopped .

Figure 2.

Page 15: Android chapter03-life-cycle

Một activity về căn bản có ba trạng thái:

1. Active / running: đang ở tại foreground của màn hình (trên đỉnh của activity stack), đang chạy.

2. Paused: mất focus, vẫn được hiển thị trên màn hìnhnhưng một activity khác đang nằm trên nó và cái activity mới này hoặc có nền trong suốt hoặc không phủ kín màn hình. Một activity ở trạng thái paused có thể bị hệ thống kill nếu ở tình trạng rất thiếu bộ nhớ.

3. Dừng (stopped) bị một activity khác che khuất hoàn toàn. Nó vẫn giữ tất cả các thông tin về trạng thái và member. Hệ thống thường kill nó nếu cần bộ nhớ cho việc khác.

1515

3. Android – Application's Life Cycle

Life Cycle States

15

Page 16: Android chapter03-life-cycle

1616

3. Android – Application's Life Cycle

Application’s Life Cycle

Figure 3.

Page 17: Android chapter03-life-cycle

17

3. Android – Application's Life Cycle

Life Cycle Events

17

Summary: APP MILESTONESNếu một activity ở trạng thái paused hay stopped, hệ thống có thể loại nó ra khỏi bộ nhớ bằng cách yêu cầu nó kết thúc (gọi phương thức finish() của nó), hoặc đơn giản là kill tiến trình của nó.

Khi nó lại được hiển thị trở lại cho người dùng, nó phải được bật lại (restart) từ đầu và khôi phục về trạng thái cũ.

Khi một activity chuyển trạng thái, nó được hệ thống thông báo về sự thay đổi đó bằng các lời gọi tới các phương thức sau (transition methods):

void onCreate(Bundle savedInstanceState) void onStart() void onRestart() void onResume()

void onPause() void onStop() void onDestroy()

Page 18: Android chapter03-life-cycle

18

3. Android – Application's Life Cycle

Life Cycle Events

18

Ta có thể override tất cả các phương thức đó để ứng dụng có hoạt động thích hợp khi trạng thái thay đổi.

(BẮT BUỘC)Tất cả các activity phải cài đặt onCreate() để thực hiện khởi tạo khi đối đượng vừa được tạo (instantiated).

(Rất nên)Nhiều activity cài onPause() để ghi nhận các thay đổi về dữ liệu (commit) và chuẩn bị cho việc ngừng tương tác với người dùng.

Page 19: Android chapter03-life-cycle

19

3. Android – Application's Life Cycle

Application’s Lifetime

19

Entire LifetimeBảy phương thức chuyển trạng thái (Figure 3) xác định toàn bộ cuộc đời của một activity.

• Toàn bộ cuộc đời của một activity bắt đầu từ lời gọi onCreate() đầu tiên tới một lời gọi onDestroy() duy nhất cuối cùng.

• Một activity thực hiện toàn bộ công việc khởi tạo trạng thái "global" tại onCreate(), và trả lại tất cả các tài nguyên còn giữ tại onDestroy().

Page 20: Android chapter03-life-cycle

20

3. Android – Application's Life Cycle

Visible Lifetime

20

Visible Lifetimevisible lifetime của một activity kéo dài từ một lời gọi onStart() tới lời gọi tương ứng tới onStop().

Trong khoảng thời gian này, người dùng có thể nhìn thấy activity đó trên màn hình, tuy nó có thể không nằm tại foreground và tương tác với người dùng.

• Các phương thức onStart() và onStop() có thể được gọi nhiều lần, khi activity chuyển giữa hai trạng thái hiện và bị che đối với người dùng.

• Giữa hai phương thức này, ta có thể giữ các tài nguyên cần thiết cho việc hiển thị activity trên màn hình.

Page 21: Android chapter03-life-cycle

21

3. Android – Application's Life Cycle

Foreground Lifetime

21

Foreground Lifetimeforeground lifetime của một activity bắt đầu từ một lời gọi onResume() và kết thúc bởi lời gọi tương ứng tới onPause().

Trong khoảng thời gian này, activity đó đứng trước mọi activity khác trên màn hình và nó tương tác với người dùng.

Một activity có thể thường xuyên chuyển qua lại giữa các trạng thái resumed và paused

Page 22: Android chapter03-life-cycle

22

3. Android – Application's Life Cycle

Life Cycle Methods

22

Method: onCreate()

• Được gọi khi activity được tạo. • Đây là nơi ta nên thực hiện khởi tạo tĩnh thông thường — tạo giao

diện người dùng (các view), nối dữ liệu với các danh sách, v.v.. • Tham số được truyền một đối tượng Bundle chứa trạng thái cũ của

activity, nếu như trạng thái đã được ghi lại.• onStart() luôn được gọi sau đó.

Page 23: Android chapter03-life-cycle

23

3. Android – Application's Life Cycle

Life Cycle Methods

23

Method: onRestart()

• Được gọi ngay trước khi activity được khởi động lại sau khi đã bị dừng (stopped).

• onStart() luôn được gọi sau đó.

Method: onStart()

• Được gọi ngay trước khi activity được hiện trên màn hình (visible).• Tiếp theo là onResume() nếu activity lên foreground, hoặc onStop()

nếu nó bị che.

Page 24: Android chapter03-life-cycle

24

3. Android – Application's Life Cycle

Life Cycle Methods

24

Method: onResume()

1.Được gọi ngay trước khi activity bắt đầu tương tác với người dùng. 2.Tại thời điểm này, activity nằm trên đỉnh activity stack và nhận input

của người dùng. 3.Tiếp theo bao giờ cùng là onPause().

Page 25: Android chapter03-life-cycle

25

3. Android – Application's Life Cycle

Life Cycle Methods

25

Method: onPause()

1.Được gọi khi hệ thống chuẩn bị chuyển sang một activity khác. 2.Phương thức này thường dùng để ghi các thay đổi chưa được lưu,

dừng hoạt hình và những công việc tốn CPU khác, v.v.. 3.Nó nên làm công việc của mình thật nhanh vì activity tiếp theo phải

đợi nó kết thúc thì mới resume được. 4.Tiếp theo là onResume() nếu activity quay lại, hoặc onStop() nếu nó

không còn được hiển thị đối với người dùng.5.Activity trong trạng thái này có thể bị hệ thống kill.

Page 26: Android chapter03-life-cycle

26

3. Android – Application's Life Cycle

Life Cycle Methods

26

Method: onStop()

1.Được gọi khi activity không còn hiển thị đối với người dùng. 2.Việc này có thể xảy ra khi nó bị hủy (destroyed), hoặc do một

activity khác (cũ hoặc mới) đã được resume và che nó. 3.Tiếp theo là onRestart() nếu activity tương tác trở loại với người

dùng, hoặc onDestroy() nếu nó không quay lại.4.Hệ thống có thể kill activity trong trạng thái này.

Page 27: Android chapter03-life-cycle

27

3. Android – Application's Life Cycle

Life Cycle Methods

27

Method: onDestroy()

1.Được gọi trước khi activity bị hủy. 2.Đây là lời gọi hàm cuối cùng mà activity nhận được. 3.Nó có thể được gọi vì activity đang kết thúc (hàm finish() của activity

được gọi), hoặc vì hệ thống đang tạm thời hủy thực thể hiện tại của activity để tiết kiệm không gian bộ nhớ.

4.Ta có thể phân biệt hai tình huống trên bằng cách dùng phương thức isFinishing().

5.Hệ thống có thể kill activity trong trạng thái này.

Page 28: Android chapter03-life-cycle

28

3. Android – Application's Life Cycle

Life Cycle Methods

28

Killable States – các trạng thái mà hệ thống kill được

• Activity ở trạng thái killable có thể bị hệ thống kết thúc bất cứ lúc nào sau khi phương thức trả về mà không thực thi thêm một dòng lệnh nào trong mã của activity.

• Ba phương thức onPause(), onStop(), và onDestroy() dẫn đến trạng thái killable.

• onPause() là phương thức duy nhất đảm bảo được gọi trước khi tiến trình bị hủy (killed) — onStop() và onDestroy() có thể không được gọi.

• Do đó, ta nên dùng onPause() để lưu dữ liệu cần giữ lại (chẳng hạn các sửa đổi của người dùng).

Page 29: Android chapter03-life-cycle

As an aside…Android Preferences

Preference là một cơ chế gọn nhẹ để lưu trữ và đọc các cặp key-value thuộc các kiểu dữ liệu cơ bản. Nó thường được dùng để lưu các preference của ứng dụng, chẳng hạn như lời chào mừng mặc định hoặc một font chữ cần nạp khi ứng dụng được bật lên.

Gọi Context.getSharedPreferences() để đọc và ghi các giá trị.

Gán tên cho tập preference của mình nếu ta muốn dùng chúng tại các component khác trong cùng một ứng dụng, hoặc dùng Activity.getPreferences() không có tên để dùng riêng cho activity đang gọi.

Ta không thể chia sẻ preference cho các ứng dụng khác (trừ khi dùng content provider). 29

3. Android – Application's Life Cycle

Life Cycle Methods

29

Page 30: Android chapter03-life-cycle

30

3. Android – Application's Life Cycle

ExampleLife Cycle

30

ExampleỨng dụng sau trình diễn một số tình huống chuyển trạng thái xảy ra trong một chu trình sống của một activity điển hình.

LAYOUT<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myScreen" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff000000" ><TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /><EditText android:id="@+id/txtColorSelect" android:hint="Background color (red, green, blue)" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText><TextView android:id="@+id/txtToDo" android:layout_width="fill_parent" android:layout_height="wrap_content"android:background="#00000000"> <!-- transparent --></TextView><Button android:text=" Finish " android:id="@+id/btnFinish" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button></LinearLayout>

Page 31: Android chapter03-life-cycle

31

3. Android – Application's Life Cycle

Example: Life Cycle

31

Code: Life Cycle Demo. Part 1package es.demo; import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.*; //GOAL: show the following life-cycle events in action

//protected void onCreate(Bundle savedInstanceState);//protected void onStart();//protected void onRestart();//protected void onResume();//protected void onPause();//protected void onStop();//protected void onDestroy();

Page 32: Android chapter03-life-cycle

32

3. Android – Application's Life Cycle

Example: Life Cycle

32

Code: Life Cycle Demo. 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);

Page 33: Android chapter03-life-cycle

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

Page 34: Android chapter03-life-cycle

34

3. Android – Application's Life Cycle

Example: Life Cycle

34

Code: Life Cycle Demo. Part 4@Overrideprotected void onPause() { super.onPause(); saveDataFromCurrentState(); Toast.makeText(this, "onPause", 1).show();}

@Overrideprotected void onRestart() { super.onRestart(); Toast.makeText(this, "onRestart", 1).show();}

@Overrideprotected void onResume() { super.onResume(); Toast.makeText(this, "onResume", 1).show();}

Page 35: Android chapter03-life-cycle

35

3. Android – Application's Life Cycle

Example: Life Cycle

35

Code: Life Cycle Demo. Part 5@Overrideprotected void onStart() { // TODO Auto-generated method stub super.onStart(); updateFromSavedState(); Toast.makeText(this, "onStart", 1).show();}

@Overrideprotected 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();}

Page 36: Android chapter03-life-cycle

36

3. Android – Application's Life Cycle

Example: Life Cycle

36

Code: Life Cycle Demo. Part 6protected 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

Page 37: Android chapter03-life-cycle

37

3. Android – Application's Life Cycle

Example: Life Cycle

37

Code: Life Cycle Demo. Part 7private static String MYPREFSID; //used in part 6private 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); }}

Page 38: Android chapter03-life-cycle

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 cu)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(); }

Page 39: Android chapter03-life-cycle

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 toreclaim 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 cu)a mình. Ví dụ, khi activity A bị hệ thôEng kill để) lấEy tài nguyển, A sẽ có cơ hội lưu trạng thái hiện hành cu)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 cu)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). (ĐôEi tượng Bundle mà phương thức này xấy dựng sẽ được truyể@n cho ca) hai phương thức khôi phục đó)*/

Page 40: Android chapter03-life-cycle

40

3. Android – Application's Life Cycle

Example: Life Cycle

40

Code: Life Cycle Demo. Part 10

@Overrideprotected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Toast.makeText(getBaseContext(), "onSaveInstanceState ...BUNDLING", Toast.LENGTH_LONG).show();} // onSaveInstanceState

}//LifeCycleDemo

Page 41: Android chapter03-life-cycle

41

3. Android – Application's Life Cycle

Example: Life Cycle

41

onCreate… onStart… onResume…

Page 42: Android chapter03-life-cycle

42

3. Android – Application's Life Cycle

Example: Life Cycle

42

onPause… onStop… onDestroy…

After pressing “Back Arrow”

Page 43: Android chapter03-life-cycle

Application’s Life Cycle

43

Questions ?

Page 44: Android chapter03-life-cycle

Application’s Life Cycle

44

AppendixLư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"); }

Page 45: Android chapter03-life-cycle

4545

3. Android – Application's Life Cycle

Homework

Your turn!EXPERIMENT 1.

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.

2. Layout tại main.xml cần có một Button (text: “Finish”, id: btnFinish) và một EditText container (txt: “” , id: txtMsg).

3. 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();4. 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

5. 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

Page 46: Android chapter03-life-cycle

4646

3. Android – Application's Life Cycle

HomeworkYour turn!EXPERIMENT 1 (cont.)

7. Dịch và chạy ứng dụng.8. Ghi lại chuỗi các message hiển thị bởi các lệnh Toast.9. Nhấn nút FINISH. Quan sát chuỗi các trạng thái.10.Chạy lại ứng dụng11.Nhấn nút HOME của emulator. Chuyện gì xảy ra?12.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ị?13.Click phím CALL của emulator. Ứng dụng ở trạng thái paused hay stopped?14.Click phím BACK để quay lại ứng dụng.15.Long-tap vào nút HANG-UP. Chuyện gì xảy ra?

Teaching notes

Page 47: Android chapter03-life-cycle

4747

3. Android – Application's Life Cycle

HomeworkYour turn!EXPERIMENT 2

16. Chạy emulator thứ hai. 1. 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)2. Gửi một text-message tới emulator thứ nhất (yêu cầu không đồng bộ -

asynchronous attention request)

17. Viết một câu vào EditText box (“these are the best moments of my life….”).

18. Chạy lại ứng dụng. Chuyện gì xảy ra đối với dòng text?

Teaching notes

Page 48: Android chapter03-life-cycle

4848

3. Android – Application's Life Cycle

HomeworkYour turn!EXPERIMENT 3Đảm bảo tính bền vững của dữ liệu (data persistency).

19. Thêm vào phương thức onPause đoạn sauSharedPreferences myFile1 = getSharedPreferences("myFile1",

Activity.MODE_PRIVATE);SharedPreferences.Editor myEditor = myFile1.edit();String temp = txtMsg.getText().toString();myEditor.putString("mydata", temp);myEditor.commit();

20. Thêm vào phương thức onResume đoạn sauSharedPreferences myFile = getSharedPreferences("myFile1",

Activity.MODE_PRIVATE);

if ( (myFile != null) && (myFile.contains("mydata")) ) {String temp = myFile.getString("mydata", "***");txtMsg.setText(temp);

}

21. Giờ thì chuyện gì xảy ra với dữ liệu đã nhập vào text box?

Teaching notes