如何从URL下载内部存储中的apk,然后在android中自动安装?

如何从URL下载内部存储中的apk,然后在android中自动安装?,android,Android,这是我的密码 mUpdateNowView是一个按钮,它是我自动下载和更新APK的onClick方法 安装apk解析错误时出错 分析包时出现问题 如何解决此错误 mUpdateNowView.setOnClickListener(updateNow); public View.OnClickListener updateNow = new View.OnClickListener() { public void onClick(View v) { try {

这是我的密码

mUpdateNowView是一个按钮,它是我自动下载和更新APK的onClick方法

安装apk解析错误时出错 分析包时出现问题

如何解决此错误

mUpdateNowView.setOnClickListener(updateNow);
public View.OnClickListener updateNow = new View.OnClickListener() {
    public void onClick(View v) {
        try {
            ProgressDialog progress;
            InstallAPK downloadAndInstall = new InstallAPK();
            progress = new ProgressDialog(SplashActivity.this);
            progress.setCancelable(false);
            progress.setMessage("Downloading...");
            downloadAndInstall.setContext(getApplicationContext(), progress);
            downloadAndInstall.execute("http://APK_URL.apk");
        } catch (Exception e) {

        }
    }
};
这是我的InstallAPK类,该类用于在内部存储器中下载apk并自动安装apk

public class InstallAPK extends AsyncTask<String, Void, Void> {

    private ProgressDialog progressDialog;
    private int status = 0;

    private Context context;

    public void setContext(Context context, ProgressDialog progress) {
        this.context = context;
        this.progressDialog = progress;
    }

    public void onPreExecute() {
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(String... arg0) {
        try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            ContextWrapper cw = new ContextWrapper(context);

            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            File myDir = new File(directory, "Android/data/MyAPK");
            myDir.mkdirs();
            File outputFile = new File(myDir, "MyAPK.apk");
            if (outputFile.exists()) {
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is ;
            int status = c.getResponseCode();
            if (status != HttpURLConnection.HTTP_OK)
               is = c.getErrorStream();
            else
               is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.flush();
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(directory, "Android/data/MyAPK/MyAPK.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
            context.startActivity(intent);


        } catch (FileNotFoundException fnfe) {
            status = 1;
            Log.e("File", "FileNotFoundException! " + fnfe);
        } catch (Exception e) {
            Log.e("UpdateAPP", "Exception " + e);
        }
        return null;
    }

    public void onPostExecute(Void unused) {
        progressDialog.dismiss();
        if (status == 1)
            Toast.makeText(context, "MyAPK Not Available", Toast.LENGTH_LONG).show();
    }
}
public类InstallAPK扩展异步任务{
私有进程对话;
私有int状态=0;
私人语境;
public void setContext(上下文上下文,进程对话框进程){
this.context=上下文;
this.progressDialog=进度;
}
公共无效onPreExecute(){
progressDialog.show();
}
@凌驾
受保护的Void doInBackground(字符串…arg0){
试一试{
URL=新URL(arg0[0]);
HttpURLConnection c=(HttpURLConnection)url.openConnection();
c、 setRequestMethod(“GET”);
c、 设置输出(真);
c、 connect();
ContextWrapper cw=新的ContextWrapper(上下文);
File directory=cw.getDir(“imageDir”,Context.MODE\u PRIVATE);
File myDir=新文件(目录“Android/data/MyAPK”);
myDir.mkdirs();
File outputFile=新文件(myDir,“MyAPK.apk”);
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos=新的FileOutputStream(outputFile);
输入流为;
int status=c.getResponseCode();
if(状态!=HttpURLConnection.HTTP\u确定)
is=c.getErrorStream();
其他的
is=c.getInputStream();
字节[]缓冲区=新字节[1024];
int len1=0;
而((len1=is.read(buffer))!=-1){
fos.写入(缓冲区,0,len1);
}
fos.flush();
fos.close();
is.close();
意向意向=新意向(意向.行动\视图);
setDataAndType(Uri.fromFile(新文件(目录,“Android/data/MyAPK/MyAPK.apk”),“application/vnd.Android.package archive”);
intent.setFlags(intent.FLAG\u活动\u新任务);
背景。开始触觉(意图);
}捕获(FileNotFoundException fnfe){
状态=1;
Log.e(“文件”,“FileNotFoundException!”+fnfe);
}捕获(例外e){
Log.e(“UpdateAPP”、“Exception”+e);
}
返回null;
}
公共void onPostExecute(void unused){
progressDialog.disclose();
如果(状态==1)
Toast.makeText(上下文,“MyAPK不可用”,Toast.LENGTH_LONG.show();
}
}
请帮帮我。
提前感谢。

以下是导致此问题的可能原因

1. Could be renaming the apk file.
2. Could be that apk file downloaded but while installing you are not referring correct path in finder.
3. Could be that the file gets corrupted and there are other reasons as well.
在我的情况下,我在有牛轧糖和以上的设备上运行应用程序,这是因为我选择了apk文件,但在使用fileProvider之前;我忘了添加xml文件和对清单文件的更改 这就是我所做的

步骤1:FileProvider是ContentProvider的一个特殊子类,它允许我们通过content://URI而不是file:///一个来安全地共享文件

<manifest>
...
<application>
    ...
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="@string/file_provider_authority"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_provider_paths" />
    </provider>
    ...
</application>
</manifest>

以下是这个问题背后可能的原因

1. Could be renaming the apk file.
2. Could be that apk file downloaded but while installing you are not referring correct path in finder.
3. Could be that the file gets corrupted and there are other reasons as well.
在我的情况下,我在有牛轧糖和以上的设备上运行应用程序,这是因为我选择了apk文件,但在使用fileProvider之前;我忘了添加xml文件和对清单文件的更改 这就是我所做的

步骤1:FileProvider是ContentProvider的一个特殊子类,它允许我们通过content://URI而不是file:///一个来安全地共享文件

<manifest>
...
<application>
    ...
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="@string/file_provider_authority"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_provider_paths" />
    </provider>
    ...
</application>
</manifest>

如果apk的最小sdk版本高于您的设备,则可能会发生这种类型的错误,请检查并获取参考android{compileSdkVersion 25 buildToolsVersion“25.0.2”defaultConfig{applicationId“com.vrvirtual.lionservices”minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName“1.0”TestInstrumentRunner“android.support.test.runner.AndroidJUnitRunner”}构建类型{发布{minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt')),'proguard rules.pro'}}}}@Redman我使用了你的应用程序的MindkVersion 15否,但你正在尝试安装的应用程序的MindkVersion是的,确保两个apk中的MindkVersion相同,只更新了versionName和versionCode。如果apk的min sdk版本高于你的设备,则可能会发生此类错误,请检查并获取参考android{compileSdkVersion 25 buildToolsVersion“25.0.2”defaultConfig{applicationId“com.vrvirtual.lionservices”minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName“1.0”testInstrumentationRunner“android.support.test.runner.AndroidJUnitRunner”}构建类型{release{minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard rules.pro'}@Redman我使用了minSdkVersion 15没有您的应用程序,但是您尝试安装的应用程序的minSdkVersion是的,确保两个apk中的minSdkVersion相同,只更新了versionName和versionCode。
Uri apkURI = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    File apkFile = new File(Environment.getExternalStorageDirectory() + "/apks/test.apk");
    apkURI = FileProvider.getUriForFile(mContext,
            BuildConfig.APPLICATION_ID + ".provider",
            apkFile);
}
else
{
    apkUri = Uri.Fromfile(apkFile);
 }


Intent intent = new Intent(Intent.VIEW);
intent.setData(apkURI);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mContext.startActivity(intent);