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

Uncategorized
275 words

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 に クリックイベント を設定する。

1
2
3
4
5
6
7
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展開して内部ストレージに保存する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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

参考