天天看點

Android 顯式Intent與隐式Intent

今日内容

  1. Intent用于頁面的切換,就拿百度這個頁面來說,一直看着搜尋框沒多少意義,點選搜尋之後的頁面才是我們上百度的原因。這就是Intent的作用。
  2. 它是什麼姑且不論,它分為兩類:顯式與隐式。

顯式Intent

Intent intent=new Intent(Context, aimContext);
startActivty(intent);
           

如果這裡有First、Second兩個頁面,而需求是要在First中打開Second頁面,代碼如下:

Intent intent=new Intent(First.this,Second.class);
startActivity(intent);
           

隐式Intent

隐式的操作主要是針對AndroidManifest而言。

對于First來說,有

<activity android:name=".First">
<Intent-filter>
<action android:name="android.intent.action.MAIN"/>
<categroy android:name="android.intent.category.LAUNCHER"/>
</intetn-filter>
</activity>
           

而對于Second來說,有

<activity android:name=".Second">
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
           

之後在java檔案中寫的時候,在顯式的基礎上稍作改動就可以了。如以下:

Intent intent=new Intent("com.example.activitytest.ACTION_START");
startActivity(intent);

           

可以發現,"com.example.activitytest.ACTION_START"的一緻是隐式Intent的特點。這裡也必須一樣。隐式的方法就是需要對應的的action和category。

Intent intent=new Intent("com.example.activitytest.ACTION_START");
           

表示想要啟動可以響應這個action的活動,而恰巧之前在AndroidManifest中給Second設定的action就是這個。即兩個action一樣。

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

這行代碼表示附加資訊。其他的不用管。但是要有,如果沒有這一行,我想"Unfortunately, XXX has stopped" 是誰也不想看到的結果。這裡插一句題外話,如果在布局layout寫了某一按鈕,但是java檔案中沒有寫findViewById,同樣也會出現這一句令我無比讨厭的提示語。

最後

添加額外的category方法:addCategroy();