如何从我的服务器更新我的Android应用程序?

时间:2016-11-19 20:21:42

标签: java android server

请帮我添加更新代码到我的应用程序,以便从我的服务器更新谢谢 没有什么工作从网,我需要完整的指南

1 个答案:

答案 0 :(得分:1)

如果没有用户权限和root访问权限,您无法安装应用程序,但可以从服务器下载应用程序新版本,然后要求用户进行安装。这是一个例子:

    {
       PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            version = info.versionName;
            if (newversion.replace(".", "") < version.replace(".", "")) {
                new DownloadFileFromURL().execute("http://exampl.com/Content/files/example.apk");
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private class DownloadFileFromURL extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = onCreateDialog();
    }

    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
            if (file.exists()) {
                file.delete();
            }
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            int lenghtOfFile = conection.getContentLength();
            pDialog.setMax(lenghtOfFile / 1024);
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/example.apk");
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress(total / 1024 + "");
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception ignored) {
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String file_url) {
        dialog.dismiss();
        File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
        if (file.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            //finish() or whatever you want
        }
    }
}