2013年8月16日 星期五

activity的啟動和返回和intent

intent:
Your app should handle reasonable Intents, which is the class Android uses to indicate what the user is trying to do and to find an appropriate app to accomplish that objective
說明:
android會依據intent尋找相關的App來給使用者挑選


利用intent

 public void startActivity(Intent intent);



ex:


Intent i = new Intent(QuizActivity.this, CheatActivity.class);
startActivity(i);


說明:
顯示另一個activity,原本activity的onStop被呼叫.
當按下back鍵後,將回到原來的activity

在activity間傳遞資訊: 透過intent的putExtra & getIntent

ex:


Intent i = new Intent(MainActivity.this, CheatActivity.class);
  boolean answerIsTrue = mAnswerKey[mCurrentIndex].isTrueQuestion();
  i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivity(i);
說明:傳送



mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
說明: 取得


Getting a result back from a child activity





1.
parent activity呼叫
public void startActivityForResult(Intent intent, int requestCode);
說明 :
之後才能夠取得child activity回傳的資料

2.
child  activity呼叫
 public final void setResult(int resultCode, Intent data);
說明:
回傳結果和Intent,資料包在intent裡。結果有2種:
Activity.RESULT_OK
Activity.RESULT_CANCELED.
這裡的intent有兩種產生方法:
1.  Intent data = new Intent();
2.  Intent i = getIntent();
     get the intent that start this activity


3. parent activity經由onActivityResult取得資料
ex:

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
          return;
        }
        mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN, false);
    }
說明:
利用requestCode判斷是從哪個activity回來




返回:
按下back鍵或是activity物件呼叫finish method


Explicit intents:
explicitly defines the component which should be called by the Android system, by using the Java class as identifier.
ex:
Intent i = new Intent(this, ActivityTwo.class);


Implicit Intents:
Implicit intents specify the action which should be performed and optionally data which provides data for the action.

ex:

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.vogella.com"));
startActivity(i);

說明:
The most commonly used intent filter is an action,






沒有留言:

張貼留言