[英]How do I programmatically download and install an apk?
我需要能够通过检查托管在某处的 apk 的更新版本(通过 versionCode/versionName)将更新推送到私人应用程序(在 Play 商店中不存在)*。
我相信我已经获得了我需要的所有代码 - 连接到 Dropbox,下载文件,触发广播接收器检查版本并安装应用程序(如果比当前版本可用)。
我的问题是 getPackageArchiveInfo 总是在下载的 apk 上返回 null。
注意:我可以在下载后手动安装该应用程序(文件未损坏),但我需要将此过程自动化。
*在这个例子中使用 Dropbox,但这不是 prod 使用的。
我使用了一些不同的资源来构建并尝试调试我的问题,请参阅:
Android:以编程方式安装 .apk
带有 Intent.VIEW_ACTION 的 Android 安装 apk 不适用于文件提供程序
compileSdkVersion 为 27,minSdkVersion 和 targetSdkVersion 为 23。这个配置很关键,不能更改。
我主要是在设置为生产设备将使用的特定配置的模拟器上进行测试,但我也在使用 Galaxy S6 进行测试。
主要活动:
public void onCheckClick(View view) {
try {
String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
txtCurrent.setText("Current: " + versionName);
String url = apkLocation;
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("description");
request.setTitle("app-debug.apk");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "app-debug.apk");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
public void onUpdateClick(View view) {
Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
installIntent.setDataAndType(Uri.parse("file:///storage/emulated/0/Download/app-debug.apk"), "application/vnd.android.package-archive");
startActivity(installIntent);
}
下载广播接收器:
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)){
//do stuff
PackageManager pm = context.getPackageManager();
String apkName = "app-debug.apk";
String fullPath = Environment.DIRECTORY_DOWNLOADS + "/" + apkName;
PackageInfo info = pm.getPackageArchiveInfo(fullPath, 0);
Toast.makeText(context, info.packageName, Toast.LENGTH_LONG).show();
}
}
安卓清单:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".DownloadBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
</intent-filter>
</receiver>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
</application>
预期:从下载的 apk 中获取版本信息,然后能够安装该 apk(如果它有更新的版本)。
实际:版本信息为空,因此无法继续该过程。
我有同样的问题。 我刚刚解决了。 这是我的解决方案:(注意:我在这里使用了 FTP 服务器,Targated SDK 23)
安卓清单:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
下载 Apk 类:
class DownloadNewVersion extends AsyncTask<String,Integer,Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressdlg = new ProgressDialog(DownloadApk.this);
progressdlg.setCancelable(false);
progressdlg.setMessage("Downloading...");
progressdlg.setProgressStyle(progressdlg.STYLE_SPINNER);
//progressdlg.setMax(100);
progressdlg.setIndeterminate(true);
progressdlg.setCanceledOnTouchOutside(false);
progressdlg.show();
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressdlg.dismiss();
if(result){
Toast.makeText(DownloadApk.this,"Done!!", Toast.LENGTH_SHORT).show();
OpenNewVersion(path);
}else{
Toast.makeText(DownloadApk.this,"Error: Server Connection Failed!", Toast.LENGTH_SHORT).show();
}
}
@Override
protected Boolean doInBackground(String... arg0) {
Boolean flag = false;
String sdcardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
String apkSavePath = sdcardRoot+"/app-debug.apk";
path=apkSavePath;
try {
String server = "103.121.78.28"; //Your download Link
int port = 21;
String user = "ftp";
String pass = "";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
String remoteFile1 = "app-debug.apk";//apk name
File downloadFile1 = new File(apkSavePath);
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
Log.d("Update", "doInBackground: "+"before if"+success);
if (success) {
Log.d("Update", "doInBackground: "+"Success"+success);
flag = true;
}
} catch (IOException ex) {
progressdlg.dismiss();
System.out.println("Error: " + ex.getMessage());
flag = false;
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
progressdlg.dismiss();
}
} catch (IOException ex) {
progressdlg.dismiss();
ex.printStackTrace();
flag = false;
}
}
} catch (Exception e) {
progressdlg.dismiss();
Log.e("TAG", "Update Error: " + e.getMessage());
e.printStackTrace();
flag = false;
}
return flag;
}
}
void OpenNewVersion(String location) {
File apkFile = new File(location);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", apkFile);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
}
startActivity(intent);;
}
// Function to check and request permission.
public void checkPermission(String permission, int requestCode)
{
if (ContextCompat.checkSelfPermission(DownloadApk.this, permission)
== PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(DownloadApk.this,
new String[] { permission },
requestCode);
}
else {
Toast.makeText(DownloadApk.this,
"Permission already granted",
Toast.LENGTH_SHORT)
.show();
}
}
// This function is called when the user accepts or decline the permission.
// Request Code is used to check which permission called this function.
// This request code is provided when the user is prompt for permission.
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super
.onRequestPermissionsResult(requestCode,
permissions,
grantResults);
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(DownloadApk.this,
"Storage Permission Granted",
Toast.LENGTH_SHORT)
.show();
}
else {
Toast.makeText(DownloadApk.this,
"Storage Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
}
}
从任何点击侦听器调用下载 Apk 类:
new DownloadNewVersion ().execute();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.