1 / 32

Chapter 7

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

novia
Télécharger la présentation

Chapter 7

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 7 Android Application Component

  2. ActivityManager

  3. ActivityManager ActivityManager can manage a variety of activities. The table below shows nested classesprovided by ActivityManager:

  4. ActivityManager 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"); } } In this section, we take “get available space of memory” as our example. The codes are shown below:

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

  6. Service

  7. Service Service是運行在背景的服務,如聽音樂時,可利用Service讓音樂在背景執行,這樣就可以關閉執行音樂的Activity來做其他事情,當要關閉音樂時,可以在抓取Service資訊後將其停止或是其他動作。 Service服務必須對應到AndroidManifest.xml。Service可由Activity來啟動,啟動之後可利用BroadcastReceiver 來取得相關Service訊息。

  8. Service 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 本節範例利用Service服務在背景執行來實作一個簡易Timer,並利用Logcat來觀看結果,範例程式碼如下:

  9. Service public 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 disc Build a ServiceClass

  10. Service <?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-sdkandroid:minSdkVersion="6" /> </manifest> To use Service, it is necessary to set Service in AndroidManifest.xml as shown below:

  11. Service Results of the example is shown below:

  12. SearchManager

  13. SearchManager SearchManager類別提供系統搜尋的服務,在正常情況下不會直接使用此類別來做應用,可利用Intent的ACTION_SEARCH或 context.getSystemService (Context.SEARCH_SERVICE)來應用搜尋服務。在許多應用程式中都會提供一個搜尋的介面,比較平常的做法是將此搜尋介面放在Menu中。 搜尋可分為兩種,「Local Search」以及「Globle Search」,Local Search搜尋範圍為應用程式定義的範圍,Globle Search則是搜尋整個系統。

  14. SearchManager 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); } } 在本範例中,實作一個簡單的搜尋範例,利用Menu以及一個EditText來實作。當Menu中有個Search的按鈕,當按下時會跳出一個簡易的快速搜尋列,而EditText中的文字則會自動被輸入至快速搜尋列當中,範例程式碼如下:

  15. SearchManager Method to start search is to use startSearch. It is used as : Parametersare listed in the table below:

  16. SearchManager Results of the example is shown below:

  17. Broadcast Receivers

  18. Broadcast Receivers BroadcastReceiver is a necessarytool in many mobile applications. When an application registers itself to BroadcastReceiver, it is allowed to use onReceiveto receive message related to the registered service. The registration method is shown below:

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

  20. Page Menu 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(); } } }; 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:

  21. Content Providers

  22. Content Providers ContentProvider可提供一個介面給所有應用程式來分享資料,而分享資料的基本格式是利用URI來當成傳遞的媒介: 而ContentProvider的scheme為「content://」,而在CONTENT_URI中的各種URI都有ID,所以在向ContentProvider指定取得某個ID的資料,如下: 在此可利用ContentUris中的withAppendedId方法來幫URI加入ID: 或是利用Uri的withAppendedPath方法加入ID

  23. Content Resolver

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

  25. Content Resolver 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)); } 在本節範例中,我們利用系統內建Phones.CONTENT_URI來得到電話中的聯絡人資訊並將其列表,範例程式碼如下:

  26. Content Resolver Query parametersof ContentResolver is listed in the table below:

  27. Content Resolver Results of the example is shown below:

  28. Content Resolver In this example, the following permission should be inserted inAndroidManifest.xml to maintain normal operation:

  29. Content Resolver 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); 上面範例是取得ContentProvider的資料,而接著介紹如何透過ContentResolver來新增資料,要達到此動作則需使用ContentValues,此範例新增一筆聯絡人資料至通訊錄中,程式碼如下:

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

  31. Content Resolver ContentResolver and its data processingis listed below:

  32. Q&A

More Related