首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 跨包啟動 Activity 的正確 Intent 寫法

     編輯:程式設計綜合問答

錯誤代碼

// 錯誤:第一個參數應為 Context,且無法跨包解析類
Intent intent = new Intent(getApplicationContext(), com.facebook.android.Places.class);

// Manifest 寫法也錯:點號開頭會被當作相對包名
<activity android:name=".com.facebook.android.Places"></activity>

正確寫法(三種等效)

  1. setClassName(推薦,最明確):
    Intent intent = new Intent();
    intent.setClassName("com.facebook.android", "com.facebook.android.Places");
    startActivity(intent);
    
  2. setComponent:
    intent.setComponent(new ComponentName("com.facebook.android", "com.facebook.android.Places"));
    
  3. 隱式 Intent + Action/Category(需目標配置):
    <!-- 目標 App Manifest -->
    <activity android:name=".Places">
        <intent-filter>
            <action android:name="com.facebook.android.SHOW_PLACES" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    
    // 調用端
    Intent intent = new Intent("com.facebook.android.SHOW_PLACES");
    startActivity(intent);
    

Manifest 正確聲明

<!-- 完整包名+類名,不加點號前綴 -->
<activity android:name="com.facebook.android.Places" 
          android:exported="true"> <!-- 必須 exported=true 允許外部啟動 -->
</activity>

常見坑

現象原因解決
ActivityNotFoundException包名/類名拼寫錯、目標未安裝、未 exportedadb shell pm list packages 確認包名;Android 12+ 必須 exported=true
SecurityException目標 Activity 權限保護 (android:permission)在調用端 Manifest 聲明 <uses-permission android:name="..."/>
啟動到錯誤 Activity隱式 Intent 匹配多個用顯式 Intent (setClassName/setComponent)

跨包啟動**永遠用顯式 Intent (setClassName/setComponent)**,隱式 Intent 易受導出組件變更影響。目標 App 必須在 Manifest 顯式聲明 android:exported="true"(Android 12+ 強制)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved