从服务器以编程方式安装apk时出错

时间:2014-03-17 07:06:37

标签: android installation apk

我需要以编程方式安装apk文件。在this post之后我将我的apk文件放在我的C:驱动器的根目录中,但我的应用程序没有正确安装。我怎么能这样做?

这是我的代码:

Button  button = (Button) findViewById(R.id.button1);

button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        canWriteOnExternalStorage();
        downloadapk();
        installApk();
    }
});

private void downloadapk(){
    try {
        URL url = new URL("http://192.168.0.108/Root.apk");
        HttpURLConnection urlConnection = (HttpURLConnection) 
                                          url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();

        File sdcard = Environment.getExternalStorageDirectory();
        File dir = new File(sdcard.getAbsolutePath() + "/nazeer/");
        dir.mkdirs();
        File file = new File(dir, "filename");

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();
        //this.checkUnknownSourceEnability();
        //this.initiateInstallation();
    } catch (MalformedURLException e) {
            e.printStackTrace();
    } catch (IOException e) {
            e.printStackTrace();
    }
}

private void installApk(){
    Intent intent = new Intent(Intent.ACTION_VIEW);

    File sdcard = Environment.getExternalStorageDirectory();
    // to this path add a new directory path
    File dir = new File(sdcard.getAbsolutePath() + "/nazeer/");

    Uri uri = Uri.fromFile(dir);  

    intent.setDataAndType(uri, "application/vnd.android.package-archive");
    startActivity(intent);
}

             after a lot of reserch finnaly i get solution using this sample code 
   http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/













        public class AndroidDownloadFileByProgressBarActivity extends Activity {

// button to show progress dialog
Button btnShowProgress;

// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0; 

// File url to download
private static String file_url = 
 "https://dl.dropboxusercontent.com/u/245131571/SampleApp.apk";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // show progress bar button
    btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
    // Image view to show image after downloading
//  my_image = (ImageView) findViewById(R.id.my_image);
    /**
     * Show Progress bar click event
     * */
    btnShowProgress.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // starting new Async Task
            new DownloadFileFromURL().execute(file_url);
        }
    });
}

/**
 * Showing Dialog
 * */
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type:
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

/**
 * Background Async Task to download file
 * */
class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            File file = new File(Environment.getExternalStorageDirectory() + 
       "/download2/");
            if (!file.exists()) {
                file.mkdir();
            }
      //      file.mkdirs();
            File outputFile = new File(file, "app.apk");
      //      FileOutputStream fos = new FileOutputStream(outputFile);

            // Output stream to write file
    //        OutputStream output = new FileOutputStream("/sdcard/SampleApp.apk");
            OutputStream output = new FileOutputStream(outputFile);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
   }

    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissDialog(progress_bar_type);



          Intent intent = new Intent(Intent.ACTION_VIEW);

                intent.setDataAndType(Uri.fromFile(new   
File(Environment.getExternalStorageDirectory() + "/download2/" + "app.apk")), 
  "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);







    }

}
  }

2 个答案:

答案 0 :(得分:0)

将apk下载到sdcard后,用apk路径调用此方法..

protected void installApp() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.fromFile(new File(Environment.getExternalStorageDirectory()
                        + File.separator + "IHS_HIV.apk")),
                "application/vnd.android.package-archive");
        startActivity(intent);
        finish();
    }

从网址

下载Apk的方法
protected void downloadFileFromUrl() {
        // TODO Auto-generated method stub

        try {

            progressBar.setProgress(progressBar.getMax() - 50);
            URL url = new URL(URL);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100%
            // progress bar
            int fileLength = connection.getContentLength();
            File file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "IHS_HIV.apk");
            file.createNewFile();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(
                    Environment.getExternalStorageDirectory() + File.separator
                            + "IHS_HIV.apk");

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

                progressBar.setProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

        } catch (Exception e) {
            ErrorLog.setErrorMessage(getApplicationContext(), e);
            Log.e("File Creating Error", e.getMessage());
        }
    }

答案 1 :(得分:0)

请使用以下代码

       public void Update(String apkurl){
  try {
        URL url = new URL(apkurl);
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        c.setRequestMethod("GET");

        c.connect();

        String PATH = Environment.getExternalStorageDirectory() + "/download/";
        File file = new File(PATH);
        file.mkdirs();
        File outputFile = new File(file, "app.apk");
        FileOutputStream fos = new FileOutputStream(outputFile);

        InputStream is = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len1);
        }
        fos.close();
        is.close();//till here, it works fine - .apk is download to my sdcard in download file

        Intent promptInstall = new Intent(Intent.ACTION_VIEW)
        .setData(Uri.parse(PATH+"app.apk"))
        .setType("application/android.com.app");
        startActivity(promptInstall);//installation is not working

    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Update error!", Toast.LENGTH_LONG).show();
    }
 }