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

AndroidManifest.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

   <!-- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />-->


    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />



    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.TNetRecv"
        tools:targetApi="31">

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>



</manifest>

Activity

java 复制代码
package com.example.tnetrecv;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.widget.VideoView;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_PERMISSION = 100;
    private static final String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE};
    private static final int REQUEST_CODE_FILE_SELECT = 101;

    private Button selectFileButton;
    private ImageView imageView;
    private  VideoView videoView;
    private ActivityResultLauncher<String> requestPermissionLauncher;
    private ActivityResultLauncher<Intent> selectFileLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videoView = findViewById(R.id.videoView);
        imageView=findViewById(R.id.imageView);
        selectFileButton = findViewById(R.id.selectFileButton);
        selectFileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPermissionAndSelectFile();
            }
        });

        // 处理权限结果
        requestPermissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        Toast.makeText(this, "已经授予读取存储权限", Toast.LENGTH_SHORT).show();
                        // 用户授予了读取存储权限
                        selectFile();
                    } else {
                        // 用户拒绝了读取存储权限
                        Toast.makeText(this, "未授予读取存储权限,无法选择文件", Toast.LENGTH_SHORT).show();
                    }
                });

        // 处理文件选择器选择后的结果
        selectFileLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    try{
                        if (result.getResultCode() == RESULT_OK) {
                            if (result.getData() != null) {
                                Uri uri = result.getData().getData();
                                String filePath = getFilePathFromUri(uri);
                               // String filePath2 = uri.toString();
                                if (filePath != null) {
                                    // 处理选中的文件路径
                                   // Log.d("AA", "选中文件:" + filePath);
                                    Toast.makeText(this, "选中文件:" + filePath, Toast.LENGTH_SHORT).show();
                                    showFileContent(filePath);
                                } else {
                                    Log.d("AA", "获取文件路径失败:" );
                                    // 获取文件路径失败
                                    Toast.makeText(this, "获取文件路径失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }catch (Exception e){
                        Log.d("AA", e.toString());
                    }

                });
    }

    //检查权限,没有的话弹出权限框
    private void checkPermissionAndSelectFile() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            // 已经获取了读取存储权限
            selectFile();
        } else {
            // 未获取读取存储权限,需要请求权限
            requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }


    private void selectFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        selectFileLauncher.launch(intent);
    }

    private void showFileContent(String filePath) {
        try {
            InputStream inputStream = getContentResolver().openInputStream(Uri.parse(filePath));
            if (inputStream != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                //读取文本
               /* StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                inputStream.close();

                String fileContent = stringBuilder.toString();
                Log.d("File Content", fileContent);*/

                //分段分段读取文本
                int chunkSize=10;
                char[] buffer = new char[chunkSize];
                int bytesRead; //用于判断是否到文件末尾的变量
                while ((bytesRead = reader.read(buffer, 0, chunkSize)) != -1) {
                    String chunk = new String(buffer, 0, bytesRead);//将字符数组的字符转换成字符串
                }





                //读取二进制图片
                   /* byte byteRead;
                    byte[] imageData=new byte[1000];// 二进制图片数据
                    int i;
                    for ( i=0;(byteRead= (byte)reader.read()) != -1&&i<imageData.length;i++) { //read()方法读取一个字符并返回器int型unicode编码
                        imageData[i]=byteRead;
                        //Log.d("File Content1", Byte.toString(byteRead));
                        Log.d("File Content2", String.valueOf(imageData));
                    }*/


                    //一次性读取图片文件
                  /*  Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse(filePath)));
                    imageView.setImageBitmap(bitmap);
                    */

                    //读取视频
                   /* Uri videoUri = Uri.parse(filePath);
                    videoView.setVideoURI(videoUri);
                    videoView.start();*/

            }
        else {
                Log.e("Error", "Failed to open input stream");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }




    private String getFilePathFromUri(Uri uri) {
        String filePath = null;
        if ("content".equals(uri.getScheme())) {
            filePath = uri.toString();
        } else if ("file".equals(uri.getScheme())) {
            filePath = uri.getPath();
        }
        return filePath;
    }






}

layout.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"

    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/selectFileButton"
        android:text="start"
        />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="400dp"
        android:layout_height="400dp" />
    <VideoView
        android:id="@+id/videoView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

项目地址:

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

相关推荐
xiangxiongfly9151 小时前
Android 圆形和圆角矩形总结
android·圆形·圆角·imageview
幻雨様7 小时前
UE5多人MOBA+GAS 45、制作冲刺技能
android·ue5
Jerry说前后端8 小时前
Android 数据可视化开发:从技术选型到性能优化
android·信息可视化·性能优化
Meteors.9 小时前
Android约束布局(ConstraintLayout)常用属性
android
alexhilton10 小时前
玩转Shader之学会如何变形画布
android·kotlin·android jetpack
whysqwhw14 小时前
安卓图片性能优化技巧
android
风往哪边走14 小时前
自定义底部筛选弹框
android
Yyyy48215 小时前
MyCAT基础概念
android
Android轮子哥15 小时前
尝试解决 Android 适配最后一公里
android
雨白16 小时前
OkHttp 源码解析:enqueue 非同步流程与 Dispatcher 调度
android