【问题标题】:Parsing Error when updating apk from within android app从 android 应用程序中更新 apk 时解析错误
【发布时间】:2014-11-17 15:42:08
【问题描述】:

我正在尝试编写一个函数来更新我的 android 应用程序,而无需在应用程序内使用 google play。我的代码很大程度上取决于thisstackoverflow 问题的答案。我已经能够解决大多数已发生的问题,但我现在收到“解析错误:解析包时出现问题”。我四处寻找这个问题的答案,我觉得我已经消除了明显的反应作为原因。我知道包没有损坏,因为我在模拟器中运行我的应用程序,然后使用监视器从数据/数据位置获取 apk 文件,将 apk 上传到我的网站,然后在我的手机上下载 apk,并从下载管理器,它工作。代码如下:

MainActivity 调用 asynctask 检查当前版本是否等同于在线最新版本。

public class MainActivity extends Activity {

ListView list;
//private ProgressBar pb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //pb.setVisibility(View.VISIBLE);

    int v = 0;
    try {
        v = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        // Huh? Really?
    }
    new CheckUpdates(this).execute(v);
}
}

如果有更新的版本,它会调用 InstallUpdate 异步任务。

private class CheckUpdates extends AsyncTask<Integer, Integer, String>{
    private Context mContext;
    private ProgressDialog pdia;

    public CheckUpdates (Context c) {
        this.mContext = c;
    }

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pdia = new ProgressDialog(mContext);
        pdia.setMessage("Checking for update...");
        pdia.show();
    }

    @Override
    protected String doInBackground(Integer... params) {
        return postData(params[0]);
    }

    @Override
    protected void onPostExecute(final String responseString){
        pdia.dismiss();

        if (!responseString.equals("")) {
            AlertDialog dialog = new AlertDialog.Builder(mContext).create();
            dialog.setTitle("Confirmation");
            dialog.setMessage("There is an update. Download and Install?");
            dialog.setCancelable(false);
            dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int buttonId) {
                    new InstallUpdate(mContext).execute("apk url");
                }
            });
            dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int buttonId) {
                }
            });
            dialog.setIcon(android.R.drawable.ic_dialog_alert);
            dialog.show();
        }
    }

    public String postData(Integer version) {
        HttpClient httpclient = new DefaultHttpClient();
        // specify the URL you want to post to
        HttpPost httppost = new HttpPost("check for update php file");
        HttpResponse response = null;
        try {
            // create a list to store HTTP variables and their values
            List nameValuePairs = new ArrayList();
            // add an HTTP variable and value pair
            nameValuePairs.add(new BasicNameValuePair("currentVersion", Integer.toString(version)));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // send the variable and value, in other words post, to the URL
            response = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            // process execption
        } catch (IOException e) {
            // process execption
        }

        HttpEntity entity = response.getEntity();
        String responseString = "";
        try {
            responseString = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            //really?
        }

        return responseString;
    }
}

如果有更新,则会调用 InstallUpdate 并下载 apk 并尝试安装它。

public class InstallUpdate extends AsyncTask<String, Integer, String> {
    private Context mContext;
    private ProgressDialog pdia;

    public InstallUpdate (Context c) {
        this.mContext = c;
    }

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pdia = new ProgressDialog(mContext);
        pdia.setMessage("Downloading update");
        pdia.setIndeterminate(false);
        pdia.setMax(100);
        pdia.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pdia.setCancelable(true);
        pdia.show();
    }

    @Override
    protected String doInBackground(String... sUrl) {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/plm/update.apk";

        try {
            URL url = new URL(sUrl[0]);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();

            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(path);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("YourApp", "Well that didn't work out so well...");
            Log.e("YourApp", e.getMessage());
        }
        return path;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        Log.v("progress", Integer.toString(progress[0]));
        pdia.setProgress(progress[0]);
    }

    // begin the installation by opening the resulting file
    @Override
    protected void onPostExecute(String path) {
        pdia.dismiss();

        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive" );
        i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Log.d("Lofting", "About to install new .apk");
        this.mContext.startActivity(i);
    }
}

我觉得问题出在 InstallUpdate asynctask postexecute 中的“this.mContext.startActivity(i)”。我不知道使用 MainActivity 的上下文是否正确,或者从 asynctask 调用它是否会导致问题。我一直试图在网上找到一个解决方案大约一个星期,但一直空着。我正在学习 java 和 android 编程,因为我一直在编写这个程序,所以我不能 100% 确定我在做什么,但这是我自己无法找到解决方案的第一个问题.

【问题讨论】:

  • 你的问题解决了吗?

标签: java android android-asynctask installation apk


【解决方案1】:

那么你的下载不成功,下载后检查apk大小必须和服务器上的一致

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多