Android 11 内部ストレージにZIP展開

アプリ開発

Android 11 にアップデートしたら、ストレージアクセスが複雑になった。

ZIP展開して内部ストレージに保存する方法を記載します。

スポンサーリンク

環境

  • Windows 11 Home 21H2
  • SDK Version API 30: Android 11.0 (R)

手順

プロジェクト作成

Empty Activity で試す。

Empty Activity

API 30: Android 11.0 (R) を選択

API 30: Android 11.0 (R)

ボタン設定

イベント発火用のボタンを付ける。

ボタン

onClickイベントを設定する。

onClickイベント

クリックイベント

MainActivity.java に クリックイベント を設定する。

public void btnClick(View view) {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("application/zip");
    intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"application/zip"});
    resultLauncher.launch(intent);
}

ZIP展開

ZIP展開して内部ストレージに保存する。

ActivityResultLauncher resultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
    if (result.getResultCode() == Activity.RESULT_OK) {
        Intent resultData = result.getData();
        if (resultData != null) {
            Uri uri = resultData.getData();
            try {
                InputStream stream = this.getContentResolver().openInputStream(uri);
                ZipInputStream is = new ZipInputStream(stream);
                while (true) {
                    ZipEntry zipEntry = is.getNextEntry();
                    if (zipEntry == null) {
                        break;
                    }
                    FileOutputStream os = this.openFileOutput(zipEntry.getName(), this.MODE_PRIVATE);
                    byte[] buffer = new byte[1024];
                    int length = 0;
                    while ((length = is.read(buffer)) > 0) {
                        os.write(buffer, 0, length);
                    }
                    os.close();
                    is.closeEntry();
                }
                is.close();
                stream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
});

実行

ボタンを押してZIPファイルを選択する。

ボタン

「/data/data/com.example.myapplication/files」にZIPが展開される。

com.example.myapplication

参考

タイトルとURLをコピーしました