android 內部存儲 更新apk

我這裏是 更新用的的,不說多的 上源碼:

public class DownloadUtil {
    private final String TAG="DownloadUtil";
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;


    private DownloadUtil(){
        okHttpClient=new OkHttpClient();
    }
    public static DownloadUtil get() {
        if(downloadUtil==null)
            downloadUtil=new DownloadUtil();
        return downloadUtil;
    }

    public void downLoad(final String url,final Context context,final OnDownloadListener listener){
        Request request=new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtil.i(TAG,"onFailure");
                listener.onDownloadFailed();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                LogUtil.i(TAG,"onResponse 1");
                int lenght=0;
                byte[] buf=new byte[2048];
                InputStream inputStream=null;
                FileOutputStream fileOutputStream=null;
                try {
                    //存儲下載文件目錄
                    String savepath = context.getFilesDir().getAbsolutePath();
                    inputStream = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savepath, getNameFromUrl(url));
                    if(file.exists()) {
                        file.delete();
                    }
                    file.getParentFile().mkdirs();
                    getRoot("chmod -R 777 "+file.getAbsolutePath());
                    fileOutputStream = new FileOutputStream(file);
                    long sum = 0;
                    while ((lenght = inputStream.read(buf)) != -1) {
                        fileOutputStream.write(buf,0,lenght);
                        sum+=lenght;
                        int progress=(int)(sum*1.0f/total*100);
                        listener.onDownloading(progress);
                    }
                    fileOutputStream.flush();
                    listener.onDownloadSuccess();
                    LogUtil.i(TAG,"onResponse over");
                }catch (Exception e){
                    listener.onDownloadFailed();
                    LogUtil.i(TAG,"onResponse Exception"+e.getMessage().toString());
                }finally {
                    try {
                        if (inputStream != null)
                            inputStream.close();
                        if (fileOutputStream != null)
                            fileOutputStream.close();
                    }catch (Exception e){
                    }
                }
                LogUtil.i(TAG,"onResponse 2");
            }
        });
    }

    /**
     * 設置權限
     * @param paramString
     * @return
     */
    public synchronized boolean getRoot(String paramString)
    {
        Process process = null;
        DataOutputStream os = null;
        try
        {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(paramString + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception localException)
        {
            System.out.println("@@@@root cmd error:"+localException);
            return false;
        }finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
                System.out.println("###root cmd error:"+e);
            }
        }
        return true;
    }
    /**
     * 從下載鏈接中解析出文件名
     * @param url
     * @return
     */
    private String getNameFromUrl(String url){
        return url.substring(url.lastIndexOf("/")+1);
    }
    public interface OnDownloadListener{
        /**
         * 下載成功
         */
        void onDownloadSuccess();

        /**
         * 下載進度
         * @param progess
         */
        void onDownloading(int progess);
        /*
        *下載失敗
         */
        void onDownloadFailed();
    }
}
//網絡
<uses-permission android:name="android.permission.INTERNET"/>
//Okhttp
compile 'com.squareup.okhttp3:okhttp:3.6.0'
//調用

DownloadUtil.get().downLoad("你自己的下載地址", context, new DownloadUtil.OnDownloadListener() {
    @Override
    public void onDownloadSuccess(final File file) {
        ((Activity)context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.getLongToast(context,R.string.update_success);

                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.parse("file://"+file.getAbsolutePath()),
                        "application/vnd.android.package-archive");
//寫的時候沒有權限  所以加上權限  
                String[] command = {"chmod", "777", file.getAbsolutePath() };
                ProcessBuilder builder = new ProcessBuilder(command);
                try {
                    builder.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                context.startActivity(intent);
            }
        });
    }

    @Override
    public void onDownloading(int progess) {
        final int progessCurrent=progess;
        ((Activity)context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                down_progress.setProgress(progessCurrent);
            }
        });
    }

    @Override
    public void onDownloadFailed() {
        ((Activity)context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.getLongToast(context,R.string.update_failed);
            }
        });
    }
});

發佈了37 篇原創文章 · 獲贊 19 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章