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

AndroidManifest.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" /><applicationandroid: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"><activityandroid: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

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;@Overrideprotected 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() {@Overridepublic 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 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"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/selectFileButton"android:text="start"/><ImageViewandroid:id="@+id/imageView"android:layout_width="400dp"android:layout_height="400dp" /><VideoViewandroid:id="@+id/videoView"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>

项目地址:

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/709659.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

链表的总结

题目&#xff1a;将26个英文字母储存在链表中 #include <stdlib.h> #include <stdio.h> struct list { char Ach; struct list* next; }; void create( struct list* head , char* ch ) 而这个head是定义在局部函数的变量&#xff0c;当出局部函数的时候&…

Kotlin的各种骚气语法

1.奇怪的中括号? 前几星期在群里见群友问这种是什么鬼,kt中有这种语法吗? 但其实这种是重写的操作符,分别是重写了setter和getter,类似于list[0]1这样 上面的两个方法声明如下: 不过这种语法很容易引起歧义,所以除非很适合的情况下不建议重写 ps:更多的操作符重载参考最下…

uniapp 部署h5,pdf预览

1.hubuilderx 打包h5。 2.上传部署包到服务器。 解压部署包&#xff1a;unzip h5.zip 。 3.nginx配置。 user root; worker_processes 1; #worker_cpu_affinity 0001 0010 0100 1000; #error_log logs/error.log; #error_log logs/error.log notice; error_log /var/l…

【工具类】repo是什么,repo常用命令,repo和git和git-repo的关系

1. repo 1. repo 1.1. repo是什么1.2. 安装1.3. repo 命令 1.3.1. repo help1.3.2. repo init1.3.3. repo sync1.3.4. repo upload1.3.5. repo start1.3.6. repo forall 1.4. mainfest 文件1.5. git-repo简介(非android repo)1.6. 参考资料 1.1. repo是什么 Repo 是一个 go…

【重温设计模式】桥接模式及其Java示例

【重温设计模式】桥接模式及其Java示例 桥接模式的介绍 今天我们要探讨的&#xff0c;正是一种名为“桥接模式”的设计模式。桥接模式&#xff0c;英文名Bridge Pattern&#xff0c;是一种结构型设计模式&#xff0c;它的主要目的是将抽象部分与实现部分分离&#xff0c;使得两…

Windows Docker 部署 Redis

部署 Redis 打开 Docker Desktop&#xff0c;切换到 Linux 内核。然后在 PowerShell 执行下面命令&#xff0c;即可启动一个 redis 服务 docker run -d --name redis -p 6379:6379 redis-如果需要自启动&#xff0c;加 --restart always 参数即可。 连接 Redis 使用客户端连…

python dictionary 字典

Python 字典 字典是另一种可变容器模型&#xff0c;且可存储任意类型对象。 字典的每个键值 key>value 对用冒号 : 分割&#xff0c;每个对之间用逗号(,)分割&#xff0c;整个字典包括在花括号 {} 中 ,格式如下 d {key1 : value1, key2 : value2, key3 : value3 }dict 作…

Vue依赖注入之Provide/Inject

1. 使用<script setup> 父组件 <template><div>这里是父组件的message值:{{ message }}</div><br /><div>这里是父组件的count值:{{ count }}</div><br /><classtest /> </template> <script setup> impor…

进程间的通信

进程间的通信方式&#xff1a; 1.管道 2.信号 3.消息队列 4.共享内存 5.信号灯 6.套接字 1.管道: 1.无名管道 无名管道只能用于具有亲缘关系的进程间通信 pipe int pipe(int pipefd[2]); 功能: 创建一个无名管道 …

上班族小王的考研与考证之路

上班族小王的考研与考证之路 小王是一名普通的上班族&#xff0c;他在一家互联网公司做产品经理。工作几年后&#xff0c;他感到自己的职业发展遇到了一些瓶颈&#xff0c;想要通过进一步的学习来提升自己。 小王首先想到的是考研。他认为&#xff0c;通过考研可以获得更高的…

SpringBoot项目中如何结合Mybatis进行数据库查询

在Spring Boot项目中使用Mybatis进行数据库操作是一种常见的实现方式。下面我将展示如何在Spring Boot项目中整合Mybatis。这个示例将包括几个主要部分&#xff1a;项目依赖配置、配置文件、实体类、Mapper接口及其XML配置文件、服务类、以及一个简单的控制器。 1. 项目依赖配…

Linux Centos7配置SSH免密登录

Linux Centos7配置SSH免密登录 配置SSH免密登录说明&#xff1a; 分两步 第一步、给Server A生成密钥对 第二步、给Server B授权 生成密钥对之后&#xff0c;我们可以看看它保存的目录下的文件。 接下来我们就要把Server A&#xff08;10.1.1.74&#xff09;的公钥拷贝到Se…

AI新秀Mistral:“Open AI“ 新时代

最近互联网出现不少类似“下一代openai”、“GPT-4最强竞品”、“法国AI独角兽”、“欧洲的OpenAI”、“微软新宠儿”.... 的文章&#xff0c;都会附带一张图片&#xff0c;就是下面这张&#xff1a; 那么到底发生了什么&#xff0c;出来个什么东西呢&#xff1f;就是本文的主…

跟着cherno手搓游戏引擎【28】第一个游戏!源码解读!逐行注释!

源码解读&#xff1a; GameLayer层级&#xff1a;在构造函数中&#xff1a;创建窗口和相机&#xff0c;对随机数种子初始化&#xff1b; 在OnAttach方法中&#xff1a;初始化关卡&#xff1a;加载资源初始化地图信息&#xff1b;设置字体&#xff1b; 在OnUpdate方法中&…

大白话解析LevelDB:LRUCache

文章目录 LRUCache 的实现思路lru_ 链表table_ 哈希表in_use_ 链表 LRUCache 的代码实现LRUCache 的定义LRUHandleLRUHandle::key, LRUHandle::hash, LRUHandle::valueLRUHandle::next_hashLRUHandle::next, LRUHandle::prevLRUHandle::chargeLRUHandle::in_cacheLRUHandle::re…

【Elasticsearch查询】查询环境

文章目录 Search查询环境routing&#xff08;路由&#xff09;自适应选择副本策略全局检索超时检索取消并发搜索terminate_aftersearch_typepreferencebatched_reduce_sizeSource禁止_source字段metrics用例数据从source中筛选字段查询 Storestored_fields映射查询 track_score…

从单体服务到微服务:多模式 Web 应用开发记录<三>预初始化属性

相关文章&#xff1a; 多模式 Web 应用开发记录<一>背景&全局变量优化多模式 Web 应用开发记录<二>自己动手写一个 Struts 开头先看一个简单的例子&#xff0c;这是 ftl 文件的一个表单&#xff1a; <form id"validateForm" action"#&quo…

【第十天】C++函数对象/仿函数、谓词、适配器及常见algorithm算法

一、函数对象 重载了函数调用运算符()的类 实例化的对象叫函数对象&#xff0c;也叫仿函数。 如果函数对象 有一个参数 叫&#xff1a;一元函数对象/仿函数如果函数对象 有二个参数 叫&#xff1a;二元函数对象/仿函数如果函数对象 有三个及以上参数 叫&#xff1a;多元函数对…

windows下基于docker-desktop 安装 mysql 5.7

0.背景 docker-desktop v4.27.1Windows 11 22H2 docker-desktop 需要wsl的支持,一般win11新机子都默认开启了,安装docker-desktop 一路next即可.win10老版本需要自行安装开启wsl.一个小建议是,如果你的win10安装wsl时各种错误无法解决,建议升级到win11大概率解决,本人亲身经历…

K8S存储卷与PV,PVC

一、前言 Kubernetes&#xff08;K8s&#xff09;中的存储卷是用于在容器之间共享数据的一种机制。存储卷可以在多个Pod之间共享数据&#xff0c;并且可以保持数据的持久性&#xff0c;即使Pod被重新调度或者删除&#xff0c;数据也不会丢失。 Kubernetes支持多种类型的存储卷…