Chapter 7

32
本本本本 本本本本本本本 本本本本本本本本本本本本本本本本本本本本本本本本本本本 本本本本本 本本本 本本本本本本本本本本本 本本本本 本本本 本本本本本本本 本本本本本本本本本本本本本本本本本 ()(),,、、( 80% 本本本本本本本本本本本本本本本 本本本本本本本 ), 本本本本本本本本 本本本本本本本本本本本本本本本本本本 本本本本本本本本本 本本本本本 本本本本本本本本本本本本本本本本 本本本本本本本本本本本本本本本本本本本本本本本本本本本本 ,、;,,。 本本本本本 © 本本本本本本本本本本 Chapter 7 Android Application Component

description

Chapter 7. Android Application Component. ActivityManager. ActivityManager. ActivityManager can manage a variety of activities. The table below shows nested classes provided by ActivityManager:. ActivityManager. public class ActivityManagerExample extends Activity { @Override - PowerPoint PPT Presentation

Transcript of Chapter 7

Page 1: Chapter 7

本投影片(下稱教用資源)僅授權給採用教用資源相關之旗標書籍為教科書之授課老師(下稱老師)專用,老師為教學使用之目的,得摘錄、編輯、重製教用資源(但使用量不得超過各該教用資源內容之 80%)以製作為輔助教學之教學投影片,並於授課時搭配旗標書籍公開播放,但不得為網際網路公開傳輸之遠距教學、網路教學等之使用;除此之外,老師不得再授權予任何第三人使用,並不得將依此授權所製作之教學投影片之相關著作物移作他用。

著作權所有 © 旗標出版股份有限公司

Chapter 7

Android Application Component

Page 2: Chapter 7

ActivityManagerActivityManager

Page 3: Chapter 7

ActivityManager

ActivityManager can manage a variety of activities. The table below shows nested classes provided by ActivityManager:

Class Name Description of Functions

ActivityManager.MemoryInfo Information related to memory

ActivityManager.ProcessErrorStateInfo Information related to process error state

ActivityManager.RecentTaskInfo Information related to related to recent task

ActivityManager.RunningAppProcessInfoInformation related to running application process

ActivityManager.RunningServiceInfo Information related to running service

ActivityManager.RunningTaskInfo Information related to running task

Page 4: Chapter 7

ActivityManager

In this section, we take “get available space of memory” as our example. The codes are shown below :

public class ActivityManagerExample extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

TextView tv = (TextView) findViewById(R.id.info);

ActivityManager myManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

// 建立 ActivityManager.MemoryInfo 物件 ActivityManager.MemoryInfo outInfo = new

ActivityManager.MemoryInfo();

// 利用 getMemoryInfo 方法獲取剩餘記憶體資訊 myManager.getMemoryInfo(outInfo);

// 將得到之記憶體大小除 1024 轉換單位為 KB

tv.setText(" 剩餘記憶體 : " + (outInfo.availMem/1024) + " KB");

}

}

Page 5: Chapter 7

ActivityManager

Results of the example is shown below. The left is the result of execution , and the right is system status display :

Page 6: Chapter 7

ServiceService

Page 7: Chapter 7

Service

Service 是運行在背景的服務,如聽音樂時,可利用 Service 讓音樂在背景執行,這樣就可以關閉執行音樂的 Activity 來做其他事情,當要關閉音樂時,可以在抓取 Service 資訊後將其停止或是其他動作。

Service 服務必須對應到AndroidManifest.xml 。 Service 可由Activity 來啟動,啟動之後可利用BroadcastReceiver 來取得相關 Service 訊息。

Page 8: Chapter 7

Service

本節範例利用 Service 服務在背景執行來實作一個簡易Timer ,並利用 Logcat 來觀看結果,範例程式碼如下:

public class ServiceExample extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

// 略 myButton.setOnClickListener(new OnClickListener(){

public void onClick(View v) {

if ( myButton.getText().equals(" 開始計時 ") ) {

myButton.setText(" 停止計時 ");

Intent i = new Intent(ServiceExample.this, myService.class);

startService(i);

}

else {

myButton.setText(" 開始計時 ");

Intent i = new Intent(ServiceExample.this, myService.class);

stopService(i);

}

}

});

}

}

Complete codes please refer to : ServiceExample.java in reference disc

Complete codes please refer to : ServiceExample.java in reference disc

Page 9: Chapter 7

Service

Build a Service Classpublic class myService extends Service {

// 此 Thread 每次迴圈會 sleep 1 秒用來計算此 Service 執行的總時間 // 並傳送 Message 訊息 // Service 尚未結束則傳送 PRINT Message

// 當接收到 Thread 傳送 Message 訊息時,若訊息內容為 PRINT 則印出 // 此 Service 目前執行的總時間,若收到 STOP 訊息時則停止 Thread 運作

// 覆寫 onStart 讓 Service 開始時執行指定的動作@Override

public void onStart (Intent intent, int startId) {

}

// 覆寫 onDestroy 讓 Service 結束時執行指定的動作@Override

public void onDestroy(){

// Service 結束時傳送 STOP Message 用來停止 Thread

}

}

Complete codes please refer to : myService.java in reference discComplete codes please refer to : myService.java in reference disc

Page 10: Chapter 7

Service

To use Service, it is necessary to set Service in AndroidManifest.xml as shown below :

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="ncu.bnlab.ServiceExample"

android:versionCode="1"

android:versionName="1.0">

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".ServiceExample"

android:label="@string/app_name">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<service

android:name=".myService"

android:exported="true">

</service>

</application>

<uses-sdk android:minSdkVersion="6" />

</manifest>

Page 11: Chapter 7

Service

Results of the example is shown below :

Page 12: Chapter 7

SearchManagerSearchManager

Page 13: Chapter 7

SearchManager

SearchManager 類別提供系統搜尋的服務,在正常情況下不會直接使用此類別來做應用,可利用 Intent 的ACTION_SEARCH 或 context.getSystemService (Context.SEARCH_SERVICE) 來應用搜尋服務。在許多應用程式中都會提供一個搜尋的介面,比較平常的做法是將此搜尋介面放在 Menu 中。

搜尋可分為兩種,「 Local Search 」以及「 Globle Search 」, Local Search 搜尋範圍為應用程式定義的範圍, Globle Search 則是搜尋整個系統。

Page 14: Chapter 7

SearchManager

在本範例中,實作一個簡單的搜尋範例,利用 Menu 以及一個EditText 來實作。當 Menu 中有個 Search 的按鈕,當按下時會跳出一個簡易的快速搜尋列,而 EditText 中的文字則會自動被輸入至快速搜尋列當中,範例程式碼如下:

public class SearchExample extends Activity {

EditText searchEdit;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

// 設定搜尋為 Local Search

setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);

searchEdit = (EditText) findViewById(R.id.SearchEdit);

}

public boolean onCreateOptionsMenu(Menu menu)

{

menu.add(0, 0, 0, "Search");

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

Bundle dataBundle = new Bundle();

String queryData = searchEdit.getText().toString();

startSearch(queryData, false, dataBundle, false);

return super.onOptionsItemSelected(item);

}

}

Page 15: Chapter 7

SearchManager

Method to start search is to use startSearch. It is used as :

Parameters are listed in the table below :

startSearch (String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch)

Class Name Description of Functions

initialQuery 若此字串不為空白,則會將此字串自動加在搜尋列上。

selectInitialQuery 若為 true,則 initialQuery會變成預設搜尋條件,當再輸入其他字會將原字串覆蓋掉。

appSearchData 應用程式可加入 application-specific額外的內容來增加搜尋的條件

globalSearch 若為 false,則看程式是否有設定,若也沒有預設設定,則自動使用Global Search方式;若為 true,則設定為 platform-global search

Page 16: Chapter 7

SearchManager

Results of the example is shown below :

Page 17: Chapter 7

Broadcast ReceiversBroadcast Receivers

Page 18: Chapter 7

Broadcast Receivers

BroadcastReceiver is a necessary tool in many mobile applications. When an application registers itself to BroadcastReceiver, it is allowed to use onReceive to receive message related to the registered service. The registration method is shown below :

registerReceiver(BroadcastReceiver receiver, IntentFilter filter)

Page 19: Chapter 7

Broadcast Receivers

onReceive 會根據程式跟系統註冊的 IntentFilter 來獲取相關服務訊息,在此簡單介紹一些關於電池與電源相關的filter 如下表:

Class Name Description of Functions

ACTION_BATTERY_CHANGED When detecting the battery status

ACTION_BATTERY_LOW When detecting the capacity of the battery is low

ACTION_BATTERY_OKAYWhen battery status turns from low-battery to normal status

ACTION_POWER_CONNECTEDWhen the device is connected to an external power supply

ACTION_POWER_DISCONNECTEDWhen the device is disconnected to an external power supply

Page 20: Chapter 7

Page Menu

Example in this section uses Toast to indicate battery status. When it changes, BroadcastReceiver will calculate the remaining capacity of the battery. Codes of the example is shown below :

private BroadcastReceiver batteryReceiver = new BroadcastReceiver()

{

int level;

int scale;

@Override

public void onReceive(Context context, Intent intent)

{

String action = intent.getAction();

// 判斷接收到的事件是否為 ACTION_BATTERY_CHANGED

if (action.equals(Intent.ACTION_BATTERY_CHANGED))

{

// 設定電池 level

level = intent.getIntExtra("level", 0);

// 設定電池 scale

scale = intent.getIntExtra("scale", 100);

// 設定 Toast 停留長短 int duration = Toast.LENGTH_LONG;

// 計算剩餘電量百分比 String text = " 剩餘電量為: " + ( level * 100 / scale ) + "%";

Toast.makeText(context, text, duration).show();

}

}

};

Page 21: Chapter 7

Content ProvidersContent Providers

Page 22: Chapter 7

Content Providers

ContentProvider 可提供一個介面給所有應用程式來分享資料,而分享資料的基本格式是利用 URI 來當成傳遞的媒介:

而 ContentProvider 的 scheme 為「 content:// 」,而在 CONTENT_URI 中的各種 URI 都有 ID ,所以在向 ContentProvider 指定取得某個 ID 的資料,如下:

在此可利用 ContentUris 中的 withAppendedId 方法來幫 URI加入 ID :

或是利用 Uri 的 withAppendedPath 方法加入 ID

<scheme> : //<authority path-abempty> "?"<query> #<fragment>

content : //. . . /35

Uri myUri = ContentUris.withAppendedId( Uri contentUri, long id );

withAppendedPath(Uri baseUri, String pathSegment);

Page 23: Chapter 7

Content ResolverContent Resolver

Page 24: Chapter 7

Content Resolver

在前面章節提到的 ContentProvider 可將 Content 分享至不同的應用程式之中,而 ContentResolver 則是一個標準的方式來取得 ContentProvider 所提供的資料,也是用來修改資料的方法,但若牽涉到寫入或修改資料的話,則要看目標的 ContentProvider 是否允許使用者對資料做存取的動作,若無此權限,則 ContentResolver 方法會失敗。

ContentProvider通常會使用 URI 的方式來當作分享資料的識別,故在 ContentResolver 要抓取某一 ContentProvider資料時則必須將要抓取的 URI 當成參數來使用。

Page 25: Chapter 7

Content Resolver

在本節範例中,我們利用系統內建 Phones.CONTENT_URI來得到電話中的聯絡人資訊並將其列表,範例程式碼如下:

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

ContentResolver cr = getContentResolver();

// Query聯絡人資料,並將結果儲存在 Cursor 中 Cursor c = cr.query(Contacts.Phones.CONTENT_URI, null, null, null, null);

phoneInfo_Name = new String[c.getCount()];

phoneInfo_Number = new String[c.getCount()];

// 先看抓取之 cusor 是否有資料 if (c.moveToFirst()) {

int nameColumn = c.getColumnIndex(Phones.NAME);

int phoneColumn = c.getColumnIndex(Phones.NUMBER);

int index = 0;

do {

phoneInfo_Name[index] = c.getString(nameColumn);

phoneInfo_Number[index] = c.getString(phoneColumn);

index++;

} while (c.moveToNext());

}

setListAdapter(new MyListAdapter(this));

}

Page 26: Chapter 7

Content Resolver

Query parameters of ContentResolver is listed in the table below :

Parameter Description of Functionsuri 欲擷取資料之 content://

projection 指定要回傳哪些欄位,若值為 null代表全部回傳selection 指定要回傳哪些列,若值為 null代表全部回傳

selectionArgs 可在回傳條件中加入「 ?」,此陣列會依序取代未知的值

sortOrder 設定回傳結果的排序方式

Page 27: Chapter 7

Content Resolver

Results of the example is shown below :

Page 28: Chapter 7

Content Resolver

In this example, the following permission should be inserted in AndroidManifest.xml to maintain normal operation :

<uses-permission android:name="android.permission.READ_CONTACTS"> </uses-permission>

Page 29: Chapter 7

Content Resolver

上面範例是取得 ContentProvider 的資料,而接著介紹如何透過ContentResolver 來新增資料,要達到此動作則需使用 ContentValues ,此範例新增一筆聯絡人資料至通訊錄中,程式碼如下:

ContentResolver cr = getContentResolver();

// 建立 ContentValues 物件ContentValues values = new ContentValues();

// 設定 People.NAME 以及 People.STARRED

values.put(People.NAME, "NCU-FAX");

values.put(People.STARRED, 0);

// 將上述設定的 ContentValues 物件 Insert 至 People.CONTENT_URI 中Uri uri = cr.insert(People.CONTENT_URI, values);

Uri phoneUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);

values.clear();

// 設定 People.Phones.TYPE (電話類型)values.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE);

// 設定 People.Phones.NUMBER (電話號碼)values.put(People.Phones.NUMBER, "03-4226062");

cr.insert(phoneUri, values);

Page 30: Chapter 7

Content Resolver

Results of the example is shown below. The left is before inserting, and the right is after inserting :

Page 31: Chapter 7

Content Resolver

ContentResolver and its data processing is listed below :

Class Name Description of Functiondelete(Uri url, String where, String[] selectionArgs) Delete the selected data

insert(Uri url, ContentValues values) Insert the selected data

query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Query the selected data

update(Uri uri, ContentValues values, String where, String[] selectionArgs) Update the selected data

Page 32: Chapter 7

Q&A