安卓應用下載自動安裝代碼

 

轉載請註明出處:https://blog.csdn.net/mr_leixiansheng/article/details/78054700

 

 

 

 

作用:下載應用、安裝應用

代碼如下:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

   <ProgressBar
       android:id="@+id/update_progress"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:max="100"
       android:visibility="gone"
       style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"/>

   <Button
       android:id="@+id/download"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:textAllCaps="false"
       android:text="download"/>

   <Button
       android:id="@+id/delete"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:textAllCaps="false"
       android:text="delete"/>
</LinearLayout>

 

 

package com.leixiansheng.autoupdate;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends AppCompatActivity {

    private static final String downloadUrl = "http://gdown.baidu.com/d" +
            "ata/wisegame/43e76ce22df64c52/QQ_730.apk";
    private int progress = 0;
    private ProgressBar progressBar;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (progressBar.getVisibility() != View.VISIBLE) {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                    progressBar.setProgress(progress);
                    if (progress == 100) {
                        progressBar.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };

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

        Button download = (Button) findViewById(R.id.download);
        Button delete = (Button) findViewById(R.id.delete);
        progressBar = (ProgressBar) findViewById(R.id.update_progress);

        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isOpenNetwork())//判斷是否有網絡
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("app下載")
                            .setMessage("是否下載")
                            .setCancelable(false)
                            .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            //下載打開APP
                                            openFile(downLoadFile(downloadUrl));
                                        }
                                    }).start();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            })
                            .show();
                }
            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File file = new File(Environment.getExternalStorageDirectory() + "/dataUpdate/update.apk");
                deleteFile(file);
            }
        });

    }

    /**
     * 網絡檢查
     */
    private boolean isOpenNetwork() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();

        if (networkInfo != null) {
            // 2.獲取當前網絡連接的類型信息
            int networkType = networkInfo.getType();
            if (ConnectivityManager.TYPE_WIFI == networkType) {
                // 當前爲wifi網絡
            } else if (ConnectivityManager.TYPE_MOBILE == networkType) {
                // 當前爲mobile網絡
            }
            return connManager.getActiveNetworkInfo().isAvailable();
        }
        return false;
    }

    /**
     * 下載APK
     */
    protected File downLoadFile(String httpUrl) {
        // TODO Auto-generated method stub
        final String fileName = "update.apk";                                                                    //文件名
//        final String fileName = httpUrl.substring(downloadUrl.lastIndexOf("/"));          //截取文件名                                                                 //文件名
        File tmpFile = new File(Environment.getExternalStorageDirectory() + "/dataUpdate");                      //指定文件夾位置
        if (!tmpFile.exists()) {
            tmpFile.mkdir();
        }
        final File file = new File(Environment.getExternalStorageDirectory() + "/dataUpdate/" + fileName);      //指定文件位置及名字

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            int fileLength = connection.getContentLength();                     //獲取下載文件長度

            if (file.exists()) {
                //如果已下載,直接打開文件
                if (file.length() == fileLength) {
                    return file;
                } else {
                    file.delete();
                }
            }

            InputStream is = connection.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[256];
            int length = 0;
            int count = 0;
            while ((length = is.read(buffer)) != -1) {
                count += length;
                progress = (int) (((float) count / fileLength) * 100);            //進度
                handler.sendEmptyMessage(1);                                       //刷新
                updateNotification(progress);                                      //通知欄更新
                fos.write(buffer, 0, length);
            }

            fos.close();
            is.close();
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 通知欄顯示下載進度
     */
    private void updateNotification(int progress) {
        //TODO
    }

    /**
     * 安裝APK
     */
    private void openFile(File file) {
        if (!file.exists()) {
            return;
        }
        Log.i("OpenFile", file.getName());
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

    /**
     * 刪除APK
     */
    private void deleteFile(File file) {
        if (file.exists()) {
            file.delete();
            Toast.makeText(this, "刪除成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "沒有可刪除文件", Toast.LENGTH_SHORT).show();

        }
    }
}

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章