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

相关推荐
2501_916008893 小时前
Web 前端开发常用工具推荐与团队实践分享
android·前端·ios·小程序·uni-app·iphone·webview
我科绝伦(Huanhuan Zhou)4 小时前
MySQL一键升级脚本(5.7-8.0)
android·mysql·adb
怪兽20145 小时前
Android View, SurfaceView, GLSurfaceView 的区别
android·面试
龚礼鹏5 小时前
android 图像显示框架二——流程分析
android
消失的旧时光-19436 小时前
kmp需要技能
android·设计模式·kotlin
帅得不敢出门6 小时前
Linux服务器编译android报no space left on device导致失败的定位解决
android·linux·服务器
雨白7 小时前
协程间的通信管道 —— Kotlin Channel 详解
android·kotlin
TimeFine9 小时前
kotlin协程 容易被忽视的CompletableDeferred
android
czhc114007566310 小时前
Linux1023 mysql 修改密码等
android·mysql·adb
GOATLong11 小时前
MySQL内置函数
android·数据库·c++·vscode·mysql