# Intent Intent分為 1. 明確意圖:**指定**開啟的Activity(之前做過的) 2. 隱含意圖:**不指定**開啟的Activity,由系統找出最適合的or詢問 e.g.點擊開啟簡報檔,系統會詢問要用內建簡報軟體還是PPT 以前用過的切換視窗(+接收額外資料) ```java= Intent intent = new Intent(); intent.setClass(MainActivity.this , ResultActivity.class); Bundle bundle = new Bundle(); bundle.putInt("Count",count); intent.putExtras(bundle); startActivity(intent); --第二頁接收bundle-- Bundle bundle=getIntent().getExtras(); int count= bundle.getInt("Count"); ``` Intent建立時可以加上要執行的ACTION ``` java= Uri number = Uri.parse("tel:5551234"); Intent callIntent = new Intent(Intent.ACTION_DIAL, number); //ACTION_DIAL為執行撥號的動作 ``` 其他還有像是ACTION_VIEW(瀏覽)、ACTION_SEND(分享)、ACTION_EDIT(編輯)等 * intent-filter 其中可包含以下三個元素: **1、<action>** 在 name 屬性中,宣告接受的意圖動作。(上一段所說的) **2、<category>** 在 name 屬性中,宣告接受的意圖類別。(像是LAUNCHER、DEFAULT 等) 若要接受隱含意圖,則category的Name屬性需設為DEFAULT **3、<data>** 指定資料 URI的scheme、host、port、 path 等 mimeType:接受的資料類型。 ```xml= ur格式:<scheme>://<host>:<port>/<path> 可以使用*要求僅部分相符的路徑名稱。 <data android:scheme="string" android:host="string" android:port="string" android:path="string" android:pathPattern="string" android:pathPrefix="string" android:mimeType="string" /> ``` e.g.要建立一個分享文字的Activity(且為隱含意圖),則可在manifests設定: ```xml= <activity android:name="ShareActivity"> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> </intent-filter> </activity> ``` > 補充:action.MAIN v.s. category.LAUNCHER > * android.intent.action.MAIN決定應用程式最先啟動的Activity > * android.intent.category.LAUNCHER決定應用程式是否顯示在程式列表裡 > >因此通常設定為action.Main的Activity,其category設為LAUNCHER(點擊列表中的應用程式圖示後開啟主activity) > Source: https://developer.android.com/guide/components/intents-filters?hl=zh-tw ### Task、Activity切換 * 按下Back > When the user presses the Back button, the current activity is popped from the top of the stack (the activity is destroyed) and the previous activity resumes (the previous state of its UI is restored). > ![](https://i.imgur.com/aBxl62N.png) * 切換工作(Task) >假設原先開啟TaskA,並依序喚醒Activity X、Y,則Task為Foregroud activity,且畫面停在Activity Y(在stack最頂端)。 >(依照上一段的說明,這時若按下Back,則Y被pop出,畫面顯示X。) >此時按下home,則TaskA移至Backgroud,等待被resume。接著開啟TaskB,並依序喚醒Activity Y、Z,就會變成下圖的情況。 >![](https://i.imgur.com/OWHkfNw.png) >Source: https://developer.android.com/guide/components/activities/tasks-and-back-stack?hl=zh-tw --- ###### tags: `Android Studio`