2014-11-17 3 views
1

앱에서 Google Play없이 안드로이드 앱을 업데이트하는 기능을 작성하려고합니다. 나는 매우 무겁게 대답에서 내 코드를 기반으로 this stackoverflow 질문. 발생한 문제의 대부분을 해결할 수 있었지만 "Parse Error : 패키지를 파싱하는 데 문제가 있습니다"라는 메시지가 나타납니다. 나는이 문제에 대한 해답을 둘러 보았고 나는 명백한 반응을 원인으로 제거했다. 나는 에뮬레이터에서 내 응용 프로그램을 실행 한 다음 데이터/데이터 위치에서 apk 파일을 가져 오기 위해 모니터를 사용하고, 내 웹 사이트에 apk를 업로드 한 다음 apk를 내 휴대 전화에서 다운로드하여 설치 한 패키지가 손상되지 않았 음을 알고 있습니다. 다운로드 관리자와 함께 작동했습니다. 다음은 코드입니다.안드로이드 앱에서 apk를 업데이트 할 때 구문 분석 오류가 발생했습니다.

MainActivity는 최신 버전이 최신 버전과 동일한 지 확인하는 asynctask를 호출합니다.

더 최신 버전이 있으면 InstallUpdate asynctask를 호출합니다.

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에서 호출하여 문제가 발생하는지는 알 수 없습니다. 나는 약 일주일 동안 온라인으로 솔루션을 찾고 계속 비워려고 노력했다. 이 프로그램을 작성하면서 자바와 안드로이드 프로그래밍을 배우고 있기 때문에 내가하는 일을 100 % 확신 할 수는 없지만 이것이 내 자신 만의 해결책을 찾을 수 없었던 첫 번째 문제입니다. .

+1

문제를 해결 했습니까? –

답변

0

다운로드가 실패했습니다. 다운로드 후 서버의 apk 크기를 확인하십시오.

관련 문제