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

相关推荐
Antonio9151 小时前
【音视频】Android NDK 与.so库适配
android·音视频
sun00770010 小时前
android ndk编译valgrind
android
AI视觉网奇11 小时前
android studio 断点无效
android·ide·android studio
jiaxi的天空11 小时前
android studio gradle 访问不了
android·ide·android studio
No Silver Bullet12 小时前
android组包时会把从maven私服获取的包下载到本地吗
android
catchadmin12 小时前
PHP serialize 序列化完全指南
android·开发语言·php
tangweiguo0305198714 小时前
Kable使用指南:Android BLE开发的现代化解决方案
android·kotlin
00后程序员张16 小时前
iOS App 混淆与资源保护:iOS配置文件加密、ipa文件安全、代码与多媒体资源防护全流程指南
android·安全·ios·小程序·uni-app·cocoa·iphone
柳岸风17 小时前
Android Studio Meerkat | 2024.3.1 Gradle Tasks不展示
android·ide·android studio
编程乐学17 小时前
安卓原创--基于 Android 开发的菜单管理系统
android