[英]Android install apk programmatically?
我在嘗試以編程方式安裝 apk 並在安裝時重新啟動 Android 模擬器時遇到了一些問題。 我提到了這個線程。
這是我的代碼:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri apkURI = FileProvider.getUriForFile(mActivity, mActivity.getApplicationContext().getPackageName() + ".provider", new File(fullPath));
intent.setDataAndType(apkURI, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivity(intent);
有沒有辦法在不啟動意圖的情況下安裝apk? 因為我在 AsyncTask 的doInBackground()
中執行上面的方法。 然后在onPostExecute()
,我需要顯示一個片段,說明安裝成功。
但是,使用上面的代碼,在調用startActivity()
它只是關閉了我的所有片段。
不幸的是,您無法在沒有用戶干預的情況下完全在后台安裝應用程序(假設這是您嘗試通過使用doInBackground()
啟動 Intent 來執行的操作)。 當您啟動該意圖時,您只需將意圖傳遞給系統的包管理器並要求它安裝它。 包管理器將需要要求用戶確認。 沒有 root 或特殊權限,即使有android.permission.INSTALL_PACKAGES
權限,您也無法真正在后台以編程方式安裝 APK。 希望這能回答你的問題!
不要忘記運行時權限
這個簡單的示例適用於API28。它打開一個apk文件,可從“下載文件夾”中安裝
為簡化起見:將要安裝的應用程序的apk文件下載到手機的“下載”文件夾中。 (有很多說明可以通過編程方式進行,也可以手動進行)
查看示例
表現
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<application
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
MainActivity調用ActivityCompat.requestPermissions(MainActivity.this, new String[]{READ_EXTERNAL_STORAGE},111);}
並接收許可
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0) {
if (requestCode == 111 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
textView.append("Permission granted write\n");
// Create Uri
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file1 = new File (downloads + "//app-debug.apk");//downloads.listFiles()[0];
Uri contentUri1 = getUriForFile(this, BuildConfig.APPLICATION_ID, file1);
// Intent to open apk
Intent intent = new Intent(Intent.ACTION_VIEW, contentUri1);
intent.setDataAndType(contentUri1, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
}
}
}
file_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="download" path="."/>
</paths>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.