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

Android 从服务器以编程方式安装apk时出错,android,installation,apk,Android,Installation,Apk,我需要以编程方式安装apk文件。接下来,我将apk文件放在C:驱动器的根目录中,但我的应用程序安装不正确。我该怎么做 这是我的密码: Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { canWriteOnExternalS

我需要以编程方式安装apk文件。接下来,我将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);







    }

}
  }
Button-Button=(Button)findViewById(R.id.button1);
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图arg0){
canWriteOnExternalStorage();
下载apk();
installApk();
}
});
私有void下载apk(){
试一试{
URL=新URL(“http://192.168.0.108/Root.apk");
HttpURLConnection urlConnection=(HttpURLConnection)
openConnection();
urlConnection.setRequestMethod(“GET”);
urlConnection.setDoOutput(true);
urlConnection.connect();
文件sdcard=Environment.getExternalStorageDirectory();
File dir=新文件(sdcard.getAbsolutePath()+“/nazeer/”;
dir.mkdirs();
文件=新文件(目录,“文件名”);
FileOutputStream fileOutput=新的FileOutputStream(文件);
InputStream InputStream=urlConnection.getInputStream();
字节[]缓冲区=新字节[1024];
int bufferLength=0;
而((bufferLength=inputStream.read(buffer))>0){
fileOutput.write(buffer,0,bufferLength);
}
fileOutput.close();
//这是。checkUnknownSourceEnable();
//此。初始化安装();
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
私有void installApk(){
意向意向=新意向(意向.行动\视图);
文件sdcard=Environment.getExternalStorageDirectory();
//向该路径添加新的目录路径
File dir=新文件(sdcard.getAbsolutePath()+“/nazeer/”;
Uri=Uri.fromFile(dir);
setDataAndType(uri,“application/vnd.android.package归档”);
星触觉(意向);
}
经过大量的研究,最终我用这个示例代码得到了解决方案
http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/
公共类AndroidDownloadFileByProgressBarActivity扩展活动{
//显示进度对话框的按钮
按钮BTN显示进度;
//进度对话框
私人对话;
图像查看我的图像;
//进度对话框类型(0-用于水平进度条)
公共静态最终整数进度条类型=0;
//要下载的文件url
私有静态字符串文件\u url=
"https://dl.dropboxusercontent.com/u/245131571/SampleApp.apk";
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//显示进度条按钮
btnShowProgress=(按钮)findViewById(R.id.btnProgressBar);
//图像视图,用于在下载后显示图像
//my_image=(ImageView)findViewById(R.id.my_image);
/**
*显示进度条单击事件
* */
btnShowProgress.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//启动新的异步任务
新建DownloadFileFromURL().execute(文件url);
}
});
}
/**
*显示对话框
* */
@凌驾
受保护的对话框onCreateDialog(int id){
开关(id){
案例进度条类型:
pDialog=新建进度对话框(此对话框);
setMessage(“正在下载文件,请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_水平);
pDialog.setCancelable(真);
pDialog.show();
返回pDialog;
违约:
返回null;
}
}
/**
*要下载文件的后台异步任务
* */
类DownloadFileFromURL扩展异步任务{
/**
*在启动后台线程之前
*显示进度条对话框
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
显示对话框(进度条类型);
}
/**
*在后台线程中下载文件
* */
@凌驾
受保护的字符串doInBackground(字符串…f_url){
整数计数;
试一试{
URL=新URL(f_URL[0]);
URLConnection conconnection=url.openConnection();
conconnect.connect();
//获取文件长度
int lenghtOfFile=conconnect.getContentLength();
//读取文件的输入流-带8k缓冲区
InputStream输入=新的BufferedInputStream(url.openStream(),8192);
File File=新文件(Environment.getExternalStorageDirectory()+
“/下载2/”;
如果(!file.exists()){
mkdir()文件;
}
//mkdirs()文件;
File outputFile=新文件(文件“app.apk”);
//FileOutputStream fos=新的FileOutputStream(outputFile);
//输出流以写入文件
//OutputStream output=新文件OutputStream(“/sdcard/SampleApp.apk”);
OutputStream output=新文件OutputStream(outputFile);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
//发布进度。。。。
//在此之后,将调用onProgressUpdate
出版进度(“+(int)((总计*100)/长度文档));
//将数据写入文件
输出.写入(数据,0,计数);
}
//冲洗输出
output.flush();
//合流
output.close();
input.close();
}捕获(例外e){
Log.e(“错误:,e.getMessage());
}
返回null;
}
/**
*更新进度条
* */
受保护的void onProgressUpdate(字符串…进度){
//按设置进度
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();
    }
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());
        }
    }
       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();
    }
 }