• 动态获取权限,文件管理器选择文件,I/O流


    AndroidManifest.xml

    1. "1.0" encoding="utf-8"?>
    2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    3. xmlns:tools="http://schemas.android.com/tools">
    4. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    5. <application
    6. android:allowBackup="true"
    7. android:dataExtractionRules="@xml/data_extraction_rules"
    8. android:fullBackupContent="@xml/backup_rules"
    9. android:icon="@mipmap/ic_launcher"
    10. android:label="@string/app_name"
    11. android:supportsRtl="true"
    12. android:theme="@style/Theme.TNetRecv"
    13. tools:targetApi="31">
    14. <activity
    15. android:name=".MainActivity"
    16. android:exported="true">
    17. <intent-filter>
    18. <action android:name="android.intent.action.MAIN" />
    19. <category android:name="android.intent.category.LAUNCHER" />
    20. intent-filter>
    21. activity>
    22. application>
    23. manifest>

    Activity

    1. package com.example.tnetrecv;
    2. import androidx.activity.result.ActivityResult;
    3. import androidx.activity.result.ActivityResultCallback;
    4. import androidx.activity.result.ActivityResultLauncher;
    5. import androidx.activity.result.contract.ActivityResultContracts;
    6. import androidx.annotation.NonNull;
    7. import androidx.appcompat.app.AlertDialog;
    8. import androidx.appcompat.app.AppCompatActivity;
    9. import androidx.core.app.ActivityCompat;
    10. import androidx.core.content.ContextCompat;
    11. import android.Manifest;
    12. import android.content.BroadcastReceiver;
    13. import android.content.Context;
    14. import android.content.Intent;
    15. import android.content.IntentFilter;
    16. import android.content.pm.PackageManager;
    17. import android.database.Cursor;
    18. import android.graphics.Bitmap;
    19. import android.graphics.BitmapFactory;
    20. import android.net.ConnectivityManager;
    21. import android.net.NetworkInfo;
    22. import android.net.Uri;
    23. import android.os.Bundle;
    24. import android.provider.MediaStore;
    25. import android.view.View;
    26. import android.widget.Button;
    27. import android.widget.ImageView;
    28. import android.widget.TextView;
    29. import android.widget.Toast;
    30. import android.util.Log;
    31. import android.widget.VideoView;
    32. import java.io.BufferedReader;
    33. import java.io.FileInputStream;
    34. import java.io.FileNotFoundException;
    35. import java.io.IOException;
    36. import java.io.InputStream;
    37. import java.io.InputStreamReader;
    38. import java.util.ArrayList;
    39. public class MainActivity extends AppCompatActivity {
    40. private static final int REQUEST_CODE_PERMISSION = 100;
    41. private static final String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE};
    42. private static final int REQUEST_CODE_FILE_SELECT = 101;
    43. private Button selectFileButton;
    44. private ImageView imageView;
    45. private VideoView videoView;
    46. private ActivityResultLauncher requestPermissionLauncher;
    47. private ActivityResultLauncher selectFileLauncher;
    48. @Override
    49. protected void onCreate(Bundle savedInstanceState) {
    50. super.onCreate(savedInstanceState);
    51. setContentView(R.layout.activity_main);
    52. videoView = findViewById(R.id.videoView);
    53. imageView=findViewById(R.id.imageView);
    54. selectFileButton = findViewById(R.id.selectFileButton);
    55. selectFileButton.setOnClickListener(new View.OnClickListener() {
    56. @Override
    57. public void onClick(View v) {
    58. checkPermissionAndSelectFile();
    59. }
    60. });
    61. // 处理权限结果
    62. requestPermissionLauncher = registerForActivityResult(
    63. new ActivityResultContracts.RequestPermission(),
    64. isGranted -> {
    65. if (isGranted) {
    66. Toast.makeText(this, "已经授予读取存储权限", Toast.LENGTH_SHORT).show();
    67. // 用户授予了读取存储权限
    68. selectFile();
    69. } else {
    70. // 用户拒绝了读取存储权限
    71. Toast.makeText(this, "未授予读取存储权限,无法选择文件", Toast.LENGTH_SHORT).show();
    72. }
    73. });
    74. // 处理文件选择器选择后的结果
    75. selectFileLauncher = registerForActivityResult(
    76. new ActivityResultContracts.StartActivityForResult(),
    77. result -> {
    78. try{
    79. if (result.getResultCode() == RESULT_OK) {
    80. if (result.getData() != null) {
    81. Uri uri = result.getData().getData();
    82. String filePath = getFilePathFromUri(uri);
    83. // String filePath2 = uri.toString();
    84. if (filePath != null) {
    85. // 处理选中的文件路径
    86. // Log.d("AA", "选中文件:" + filePath);
    87. Toast.makeText(this, "选中文件:" + filePath, Toast.LENGTH_SHORT).show();
    88. showFileContent(filePath);
    89. } else {
    90. Log.d("AA", "获取文件路径失败:" );
    91. // 获取文件路径失败
    92. Toast.makeText(this, "获取文件路径失败", Toast.LENGTH_SHORT).show();
    93. }
    94. }
    95. }
    96. }catch (Exception e){
    97. Log.d("AA", e.toString());
    98. }
    99. });
    100. }
    101. //检查权限,没有的话弹出权限框
    102. private void checkPermissionAndSelectFile() {
    103. if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
    104. == PackageManager.PERMISSION_GRANTED) {
    105. // 已经获取了读取存储权限
    106. selectFile();
    107. } else {
    108. // 未获取读取存储权限,需要请求权限
    109. requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
    110. }
    111. }
    112. private void selectFile() {
    113. Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    114. intent.setType("*/*");
    115. selectFileLauncher.launch(intent);
    116. }
    117. private void showFileContent(String filePath) {
    118. try {
    119. InputStream inputStream = getContentResolver().openInputStream(Uri.parse(filePath));
    120. if (inputStream != null) {
    121. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    122. //读取文本
    123. /* StringBuilder stringBuilder = new StringBuilder();
    124. String line;
    125. while ((line = reader.readLine()) != null) {
    126. stringBuilder.append(line).append("\n");
    127. }
    128. inputStream.close();
    129. String fileContent = stringBuilder.toString();
    130. Log.d("File Content", fileContent);*/
    131. //分段分段读取文本
    132. int chunkSize=10;
    133. char[] buffer = new char[chunkSize];
    134. int bytesRead; //用于判断是否到文件末尾的变量
    135. while ((bytesRead = reader.read(buffer, 0, chunkSize)) != -1) {
    136. String chunk = new String(buffer, 0, bytesRead);//将字符数组的字符转换成字符串
    137. }
    138. //读取二进制图片
    139. /* byte byteRead;
    140. byte[] imageData=new byte[1000];// 二进制图片数据
    141. int i;
    142. for ( i=0;(byteRead= (byte)reader.read()) != -1&&i
    143. imageData[i]=byteRead;
    144. //Log.d("File Content1", Byte.toString(byteRead));
    145. Log.d("File Content2", String.valueOf(imageData));
    146. }*/
    147. //一次性读取图片文件
    148. /* Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse(filePath)));
    149. imageView.setImageBitmap(bitmap);
    150. */
    151. //读取视频
    152. /* Uri videoUri = Uri.parse(filePath);
    153. videoView.setVideoURI(videoUri);
    154. videoView.start();*/
    155. }
    156. else {
    157. Log.e("Error", "Failed to open input stream");
    158. }
    159. } catch (IOException e) {
    160. e.printStackTrace();
    161. }
    162. }
    163. private String getFilePathFromUri(Uri uri) {
    164. String filePath = null;
    165. if ("content".equals(uri.getScheme())) {
    166. filePath = uri.toString();
    167. } else if ("file".equals(uri.getScheme())) {
    168. filePath = uri.getPath();
    169. }
    170. return filePath;
    171. }
    172. }

    layout.xml

    1. "1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. xmlns:app="http://schemas.android.com/apk/res-auto"
    4. xmlns:tools="http://schemas.android.com/tools"
    5. android:layout_width="match_parent"
    6. android:layout_height="match_parent"
    7. android:orientation="vertical"
    8. tools:context=".MainActivity">
    9. <Button
    10. android:layout_width="wrap_content"
    11. android:layout_height="wrap_content"
    12. android:id="@+id/selectFileButton"
    13. android:text="start"
    14. />
    15. <ImageView
    16. android:id="@+id/imageView"
    17. android:layout_width="400dp"
    18. android:layout_height="400dp" />
    19. <VideoView
    20. android:id="@+id/videoView"
    21. android:layout_width="wrap_content"
    22. android:layout_height="wrap_content" />
    23. LinearLayout>

    项目地址:

    https://gitee.com/angel_apple/android-work.git

  • 相关阅读:
    第46屆ICPC 東亞洲區域賽(澳門)
    [SpringMVC笔记] SpringMVC-14-SSM整合-异常处理器
    树形dp,LeetCode 2385. 感染二叉树需要的总时间
    了解的Java泛型
    002 Python基础
    阿里二面:JVM调优你会吗?
    win命令行中导入、导出数据库相关表
    微信公众号菜单管理接口开发
    STM32F4-ADC-常规通道-转换模式配置-总结
    手把手教你配置Linux深度学习服务器-不用本地安装!
  • 原文地址:https://blog.csdn.net/qq_63053996/article/details/136358719