標籤:android intent
Intent是意圖的意思,分為顯式 Intent 和隱式 Intent。下面我們試圖在FirstActivity中通過點擊按鈕來啟動SecondActivity
1.顯式Intent
在應用中建立兩個類,FirstActivity和SecondActivity。分別為它們建立layout布局檔案first_layout,second_layout,並在AndroidManifest.xml中註冊。
Intent的用法: Intent(Context packageContext, Class cls)。
這個建構函式接收兩個參數,第一個參數 Context 要求提供一個啟動活動的上下文,第二個參數 Class 則是指定想要啟動的目標活動, 通過這個建構函式就可以構建出 Intent 的“意圖”。
將FirstActivity中button1的響應事件修改為
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
光有意圖還不夠,Activity 類中提供了一個 startActivity()方法,這個方法是專門用於啟動活動的,它接收一個 Intent參數,這裡我們將構建好的 Intent傳入 startActivity()方法就可以啟動目標活動了。
2.隱式意圖
隱式Intet並不明確指出我們想要啟動哪一個活動,而是指定了一系列更為抽象的 action 和 category 等資訊,然後交由系統去分析這個 Intent,
並幫我們找出合適的活動去啟動。
AndroidManifest.xml中在SecondActivity裡添加
<intent-filter><action android:name="com.example.activitytest.ACTION_START" /><category android:name="android.intent.category.DEFAULT" /></intent-filter>
然後修改 FirstActivity 中按鈕的點擊事件
Intent intent = new Intent(“com.example.activitytest.ACTION_START”);
startActivity(intent);
因為動作相匹配,而類別是預設的,所以也能啟動SecondActivity
每個 Intent 中只能指定一個 action,但卻能指定多個 category。目前我們的 Intent 中只有一個預設的 category,那麼現在再來增加一個吧。
Intent intent = new Intent(“com.example.activitytest.ACTION_START”);
intent.addCategory(“com.example.activitytest.MY_CATEGORY”);
startActivity(intent);
那麼,我們在AndroidManifest.xml中註冊的活動也要修改相應的類別才能響應這個Intent
<intent-filter> <action android:name="com.example.activitytest.ACTION_START"/> <category android:name="android.intent.category.DEFAULT" /> <category android:name="com.example.activitytest.MY_CATEGORY"/> </intent-filter>
再次重新啟動程式,就ok了。
3.隱式Intent的另一個功能:顯示網頁
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(“http://www.baidu.com“));
startActivity(intent);
uri是統一資源識別項的縮寫,先將百度的網址轉化成統一資源識別項,然後在傳入intent,ACTION_VIEW會根據傳入的資料類型開啟相應的活動,本例中開啟的是網頁,也可以開啟撥號程式,地圖定位等。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Android筆記(五)利用Intent啟動活動