gpt4 book ai didi

java - 如何以编程方式下载和安装 apk?

转载 作者:行者123 更新时间:2023-12-05 00:06:05 27 4
gpt4 key购买 nike

我需要能够通过检查某处托管的 apk 的较新版本(通过 versionCode/versionName)来推送对私有(private)应用程序(Play 商店中不存在)的更新*。

我相信我已经获得了我需要的所有代码 - 连接到 Dropbox,下载文件,触发广播接收器检查版本并安装应用程序(如果有比当前版本更新的版本可用)。

我的问题是 getPackageArchiveInfo 总是在下载的 apk 上返回 null。

注意:我可以在下载应用程序后手动安装它(文件未损坏),但我需要这个过程自动化。

*在此示例中使用 Dropbox,但这不是 prod 使用的。

我使用了一些不同的资源来构建并尝试调试我的问题,请参阅:
Android: install .apk programmatically
Android install apk with Intent.VIEW_ACTION not working with File provider

compileSdkVersion是27,minSdkVersion和targetSdkVersion是23,这个配置很关键,不能改。

我主要在设置为生产设备将使用的特定配置的模拟器上进行测试,但我也使用 Galaxy S6 进行测试。

主要 Activity :

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();
}
}

安卓 list :

<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 有更新的版本,则能够安装该 apk。
实际:版本信息为空,无法继续处理。

最佳答案

我遇到了同样的问题。我刚刚解决了它。这是我的解决方案:(注意:我在这里使用了 FTP 服务器,Targated SDK 23)

安卓 list :

<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();

关于java - 如何以编程方式下载和安装 apk?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55732011/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com