2011年4月6日 星期三

Intent & Bundle物件

Intent & Bundle物件

Intent
用於應用程式之間的通訊,例如說從一個Activity要呼叫其他的Activity(Server...)

程式碼
    Intent intent = new Intent(Test.this, Test2.class);
    startActivity(intent);
    startService(intent);

另外Intent裡也可以放入"動作"屬性
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
    startActivity
(intent);

若是需要回傳值的時候可以使用"startActivityForResult()"的方法,如下
    private void pickContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
        startActivityForResult
(intent, PICK_CONTACT_REQUEST);
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
    
        // coding the function which you want to do
       
}
    }


IntentFilter
當Intent元件之間在傳遞時,若需要告知Android系統自己能夠回應或處理哪些Intent,則可以使用IntentFilter物件。
IntentFilter可以過濾元件無法回應及處理的Intent,只將自己的Intent接收進來處理。
通常應用於Boradcast Receiver元件上。

PendingIntent
在Service裡無法使用startActivity()這種方法,這時候就可以使用PendingIntent這個物件

程式碼
    Intent intent = new Intent(this,Test.class);
    PendingIntent pending =
        PendingIntent.getActivity(
            this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
        pending.send();
    } catch (CanceledException e) {
        e.printStackTrace();
    }

Bundle
用來傳送不同程序間的資料,通常與Intent一起使用

程式碼
    Test.java
    Intent intent = new Intent(this,Test.class);
    Bundle bundle = new Bundle();
    bundle.putInt("brightness", value);
    intent.putExtras(bundle);

    Test2.java
    Bundle bundle = this.getIntent().getExtras();
    int value = bundle.getInt("brightness");

沒有留言:

張貼留言