Android 检查应用程序更新并下载,然后安装

Android 检查应用程序更新并下载,然后安装,android,Android,如何检查应用程序更新和下载,然后安装它? 我想对检查版本使用改型。例如,服务器返回以下内容: json: 在应用程序中,仅在应用程序内启动(非onresume、onback等),将新版本与旧版本进行比较,如果存在新版本,则为用户显示警报对话框,如果选择了“是”,则下载它并在下载后运行安装程序。 如何做到这一点?获取应用程序版本: try { PackageInfo info=this.getPackageManager().getPackageInfo(getPackageNam

如何检查应用程序更新和下载,然后安装它? 我想对检查版本使用改型。例如,服务器返回以下内容: json:

在应用程序中,仅在应用程序内启动(非onresume、onback等),将新版本与旧版本进行比较,如果存在新版本,则为用户显示警报对话框,如果选择了“是”,则下载它并在下载后运行安装程序。 如何做到这一点?

获取应用程序版本:

try {
        PackageInfo info=this.getPackageManager().getPackageInfo(getPackageName(),0);
        String versionName=info.versionName;
        float thisAppVersion=Float.valueOf(versionName);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
 if(version_from_net>thisAppVersion(
 showUpdateDialog();
 )
更新和显示对话框的方法:

private void showUpdateDialog(final String url,String message) {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setView(R.layout.update_dialog_layout);
        final AlertDialog dialog=builder.show();
        Button ok,cancel;
        TextView messageText=dialog.findViewById(R.id.update_dialog_message);
        messageText.setText(message);
        ok=dialog.findViewById(R.id.update_dialog_ok_btn);
        cancel=dialog.findViewById(R.id.update_dialog_cancel_btn);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
                MainActivity.this.finish();
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File extFile=getExternalFilesDir(null);
                File tempDir=new File(extFile,"temp");
                File tempApp=new File(tempDir,"temp.apk");
                if (tempApp.exists()){
                    dialog.cancel();
                    APKLauncher launcher=new APKLauncher(MainActivity.this,tempApp);
                    launcher.lunchAPK();
                }else {
                    dialog.cancel();
                    update(url);
                }
            }
        });
    }

    private void update(String url) {
        ProgressDialog dialog=new ProgressDialog(this);
        dialog.setCancelable(false);
        dialog.setMessage("downloading ...");
        dialog.setIndeterminate(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMax(100);

        UpdateApp updateApp=new UpdateApp(this,dialog);
        updateApp.execute(url);

    }
UpdateApp类:

public class UpdateApp extends AsyncTask<String,String,Void> {
    ProgressDialog progressDialog;
    int status=0;
    private Activity activity;

    public UpdateApp( Activity activity,ProgressDialog progressDialog) {
        this.progressDialog = progressDialog;
        this.activity = activity;
    }

    @Override
    protected Void doInBackground(String... strings) {
        try {
            int count = 0;
            URL url=new URL(strings[0]);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int lengthOfFile=connection.getContentLength();
            File location = activity.getExternalFilesDir(null);
            File temp=new File(location,"temp");
            if (!temp.exists()){
                temp.mkdir();
            }
            File outputFile=new File(temp,"temp.apk");
            if (outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos=new FileOutputStream(outputFile);
            InputStream is=connection.getInputStream();
            byte[] buffer=new byte[1024];
            int len=0;
            while ((len=is.read(buffer))!=-1){
                count+=len;
                publishProgress(""+(int)((count*100)/lengthOfFile));
                fos.write(buffer,0,len);
            }
            fos.flush();
            fos.close();
            is.close();
            APKLauncher launcher=new APKLauncher(activity,outputFile);
            launcher.lunchAPK();

        } catch (IOException e) {
            e.printStackTrace();
            status=1;
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        progressDialog.show();
    }

    @Override
    protected void onProgressUpdate(String... values) {
        progressDialog.setProgress(Integer.valueOf(values[0]));

    }

    @Override
    protected void onPostExecute(Void aVoid) {
        progressDialog.cancel();
        if (status==1){
            activity.finish();
        }
    }
}
对于“创建文件提供程序”阅读教程:

public class UpdateApp extends AsyncTask<String,String,Void> {
    ProgressDialog progressDialog;
    int status=0;
    private Activity activity;

    public UpdateApp( Activity activity,ProgressDialog progressDialog) {
        this.progressDialog = progressDialog;
        this.activity = activity;
    }

    @Override
    protected Void doInBackground(String... strings) {
        try {
            int count = 0;
            URL url=new URL(strings[0]);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int lengthOfFile=connection.getContentLength();
            File location = activity.getExternalFilesDir(null);
            File temp=new File(location,"temp");
            if (!temp.exists()){
                temp.mkdir();
            }
            File outputFile=new File(temp,"temp.apk");
            if (outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos=new FileOutputStream(outputFile);
            InputStream is=connection.getInputStream();
            byte[] buffer=new byte[1024];
            int len=0;
            while ((len=is.read(buffer))!=-1){
                count+=len;
                publishProgress(""+(int)((count*100)/lengthOfFile));
                fos.write(buffer,0,len);
            }
            fos.flush();
            fos.close();
            is.close();
            APKLauncher launcher=new APKLauncher(activity,outputFile);
            launcher.lunchAPK();

        } catch (IOException e) {
            e.printStackTrace();
            status=1;
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        progressDialog.show();
    }

    @Override
    protected void onProgressUpdate(String... values) {
        progressDialog.setProgress(Integer.valueOf(values[0]));

    }

    @Override
    protected void onPostExecute(Void aVoid) {
        progressDialog.cancel();
        if (status==1){
            activity.finish();
        }
    }
}
    public class APKLauncher {
        private Activity activity;
        private File tem

pFile;

    public APKLauncher(Activity activity, File tempFile) {
        this.activity = activity;
        this.tempFile = tempFile;
    }
    public void lunchAPK(){
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            Uri uri=FileProvider.getUriForFile(activity,BuildConfig.APPLICATION_ID+".provider",tempFile);
            Intent intent=new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, MimeTypeMap.getSingleton().getMimeTypeFromExtension("apk"));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            activity.startActivityForResult(intent, Const.UPDATE_REQUEST_CODE);
        }else {
            Uri uri=Uri.fromFile(tempFile);
            Intent intent=new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, MimeTypeMap.getSingleton().getMimeTypeFromExtension("apk"));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivityForResult(intent, Const.UPDATE_REQUEST_CODE);
        }
        }
    }