Android進程間使用Intent進行通信
安卓使用Intent來封裝程序的“調(diào)用意圖”,使用Intent可以讓程序看起來更規(guī)范,更易于維護。
除此之外,使用Intent還有一個好處:有些時候我們只是想要啟動具有某種特征的組件,并不想和某個具體的組件耦合,使用Intent在這種情況下有利于解耦。
Action,Category屬性與intent-filter配置
我們知道當(dāng)需要進行Activity跳轉(zhuǎn)的時候需要在manifests.xml文件中配置Activity信息。其中主Activity還需要配置<intent-filter>,并且在標(biāo)簽中還要配置<action>和<category>兩個標(biāo)簽。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AcitvityTest"
tools:targetApi="31">
<activity android:name=".lifecycle.SecondActivity"/>
<activity
android:name=".lifecycle.FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
</application>
</manifest>其中Action代表該Intent所要完成的一個抽象“動作”,而category則用于為Action增加額外的附加類別信息。通常Action屬性會與Category屬性結(jié)合使用。
<action>和<category>兩個標(biāo)簽中都可以指定android:name屬性,該屬性的值實際上就是字符串,<action>標(biāo)簽中的屬性表明該Activity能夠響應(yīng)哪些Intent。
<intent-filer>標(biāo)簽實際上就是IntentFilet對象,用于聲明該組件(比如Activity,Service,BroadcastReceiver)能夠滿足多少要求,每個組件可以聲明自己滿足多個Action要求,多個Category要求。只要某個組件能滿足的要求大于等于Intent所指定的要求,那么該Intent就能啟動該組件。
一個Intent對象只能包含一個Action屬性,通過setAction(Stirng str)方法來進行設(shè)置,一個Intent對象可以包含多個Category屬性,通過addCategory(String str)方法來進行添加。
當(dāng)然,我們也可以通過設(shè)置Intent的Action和Category屬性來跳轉(zhuǎn)到系統(tǒng)的Activity
public class HomeActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button button = findViewById(R.id.home);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
});
}
}上述代碼中配置的Action和Category對應(yīng)的就是系統(tǒng)桌面,點擊按鈕后就會返回桌面。


到此這篇關(guān)于Android進程間使用Intent進行通信的文章就介紹到這了,更多相關(guān)Android Intent通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android?App實現(xiàn)閃屏頁廣告圖的全屏顯示實例
這篇文章主要為大家介紹了Android?App實現(xiàn)閃屏頁廣告圖的全屏顯示實例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08
android app跳轉(zhuǎn)應(yīng)用商店實現(xiàn)步驟
這篇文章主要為大家介紹了android app跳轉(zhuǎn)應(yīng)用商店實現(xiàn)步驟詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11
Android定制RadioButton樣式三種實現(xiàn)方法
三種方法實現(xiàn)Android定制RadioButton樣式:使用XML文件進行定義/在JAVA代碼中定義等等,感興趣的朋友可以參考下,希望可以幫助到你2013-02-02
Android?Java?try?catch?失效問題及解決
這篇文章主要介紹了Android?Java?try?catch?失效問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11

