动态获取权限,文件管理器选择文件,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

相关推荐
CYRUS STUDIO5 分钟前
ARM64汇编寻址、汇编指令、指令编码方式
android·汇编·arm开发·arm·arm64
weixin_449310841 小时前
高效集成:聚水潭采购数据同步到MySQL
android·数据库·mysql
Zender Han1 小时前
Flutter自定义矩形进度条实现详解
android·flutter·ios
白乐天_n3 小时前
adb:Android调试桥
android·adb
姑苏风7 小时前
《Kotlin实战》-附录
android·开发语言·kotlin
数据猎手小k10 小时前
AndroidLab:一个系统化的Android代理框架,包含操作环境和可复现的基准测试,支持大型语言模型和多模态模型。
android·人工智能·机器学习·语言模型
你的小1011 小时前
JavaWeb项目-----博客系统
android
风和先行11 小时前
adb 命令查看设备存储占用情况
android·adb
AaVictory.12 小时前
Android 开发 Java中 list实现 按照时间格式 yyyy-MM-dd HH:mm 顺序
android·java·list
似霰13 小时前
安卓智能指针sp、wp、RefBase浅析
android·c++·binder