1. 程式人生 > >Android 內建儲存空間的操作。

Android 內建儲存空間的操作。

1,開發中遇到沒有內建SDK的情況。之前沒搞過,今天搞了一下午。終於找到原因了,特此記下來。
首先感謝這位:http://aijiawang-126-com.iteye.com/blog/792931

我的網路請求用的是OKGO。
直接貼程式碼

/**
     * APP下載
     *
     * @param url
     * @param fileName APP名字 最近從新命的名字
     */
    public void downLoadApp(String url, final String fileName) {

        OkGo.<File>get(url)
                .tag(this
) .execute(new FileCallback(getApplicationContext().getDir("app", MODE_WORLD_WRITEABLE) + "/", fileName) { @Override public void onStart(Request<File, ? extends Request> request) { super.onStart(request); //6.0 以上要手動給許可權。
verifyStoragePermissions(GameActivity.this); // crateFile(""); showDialog(); } @Override public void onSuccess(Response<File> response) {// hud.dismiss(); // 這個是關鍵,給指定檔案許可權
setUpdateDir(new File(getApplicationContext().getDir("app", MODE_WORLD_WRITEABLE) + "/" + fileName)); //安裝APP installApp(getApplicationContext().getDir("app", MODE_WORLD_WRITEABLE) + "/" + fileName); } @Override public void onError(Response<File> response) { super.onError(response); Toast.makeText(GameActivity.this, "下載失敗,請檢查!", Toast.LENGTH_SHORT).show(); } @Override public void downloadProgress(Progress progress) { super.downloadProgress(progress); Log.e("包路徑---", "" + progress.fraction); } @Override public void onFinish() { super.onFinish(); hud.dismiss(); } }); }

下面是兩個方法

  //根據指定路徑安裝APP
    private void installApp(String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + path),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }
/**
     * 內建儲存中給指定的檔案許可權。
     *
     * @param updateDir 檔案路徑位置
     */
    private void setUpdateDir(File updateDir) {
        try {
            Process p = Runtime.getRuntime().exec("chmod 777 " + updateDir);
            int status = p.waitFor();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }