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

Android 程序安裝 APK:Intent.ACTION_VIEW 正確 MIME 類型

     編輯:程式設計綜合問答

錯誤代碼

intent.setData(Uri.parse(path));
intent.setType("application/android.com.app"); // 錯誤 MIME

正確 MIME

intent.setDataAndType(
    Uri.fromFile(new File(apkPath)),
    "application/vnd.android.package-archive"
);

完整安裝流程

File apkFile = new File(Environment.getExternalStorageDirectory(), "download/app.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Android 7+ 必須
startActivity(intent);

Android 7+ (API 24) 適配

  • 禁止 file:// Uri,必須用 FileProvider 生成 content:// Uri。
  • Manifest 配置 <provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
  • 代碼:Uri uri = FileProvider.getUriForFile(context, authority, file);

Android 8+ (API 26) 未知來源安裝權限

需引導用戶開啟「允許安裝未知應用」權限,或使用 PackageInstaller 會話安裝(系統應用/設備管理員)。

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