記一次在android的學(xué)習(xí)中遇到的SD卡權(quán)限問題。最開始題主本來是想做一個小的demo來操作SD卡遮婶。如圖所示:
沒想到在開發(fā)的過程中遇到了權(quán)限問題。
首先貼一下activity的代碼。其實就是三個按鈕嘲恍,綁定三個事件息堂。
```java
package com.example.demo;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.io.IOException;
/**
* @Author godv
* Date on 2020/4/14? 22:02
*/
public class FileActivity extends AppCompatActivity {
? ? private EditText editname;
? ? private EditText editdetail;
? ? private Button btnsave;
? ? private Button btnclean;
? ? private Button btnread;
? ? private Context mContext;
? ? private static final int REQUEST_EXTERNAL_STORAGE = 1;
? ? private static String[] PERMISSIONS_STORAGE = {
? ? ? ? ? ? "android.permission.READ_EXTERNAL_STORAGE",
? ? ? ? ? ? "android.permission.WRITE_EXTERNAL_STORAGE" };
? ? /*
? ? * android 動態(tài)權(quán)限申請
? ? * */
? ? public static void verifyStoragePermissions(Activity activity) {
? ? ? ? try {
? ? ? ? ? ? //檢測是否有寫的權(quán)限
? ? ? ? ? ? int permission = ActivityCompat.checkSelfPermission(activity,
? ? ? ? ? ? ? ? ? ? "android.permission.WRITE_EXTERNAL_STORAGE");
? ? ? ? ? ? if (permission != PackageManager.PERMISSION_GRANTED) {
? ? ? ? ? ? ? ? // 沒有寫的權(quán)限嚷狞,去申請寫的權(quán)限块促,會彈出對話框
? ? ? ? ? ? ? ? ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
? ? ? ? ? ? }
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
? ? @Override
? ? protected void onCreate(@Nullable Bundle savedInstanceState) {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? setContentView(R.layout.file_layout);
? ? ? ? verifyStoragePermissions(this);
? ? ? ? mContext = getApplication();
? ? ? ? editdetail = (EditText) findViewById(R.id.editdetail);
? ? ? ? editname = (EditText) findViewById(R.id.editname);
? ? ? ? btnclean = (Button) findViewById(R.id.btnclean);
? ? ? ? btnsave = (Button) findViewById(R.id.btnsave);
? ? ? ? btnread = (Button) findViewById(R.id.btnread);
? ? ? ? //清空
? ? ? ? btnclean.setOnClickListener(new View.OnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v) {
? ? ? ? ? ? ? ? editdetail.setText("");
? ? ? ? ? ? ? ? editname.setText("");
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? //保存
? ? ? ? btnsave.setOnClickListener(new View.OnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v) {
? ? ? ? ? ? ? ? FileHelper fHelper = new FileHelper(mContext);
? ? ? ? ? ? ? ? String filename = editname.getText().toString();
? ? ? ? ? ? ? ? String filedetail = editdetail.getText().toString();
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? fHelper.savFileToSD(filename, filedetail);
? ? ? ? ? ? ? ? ? ? Toast.makeText(getApplicationContext(), "數(shù)據(jù)寫入成功", Toast.LENGTH_SHORT).show();
? ? ? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? ? ? Toast.makeText(getApplicationContext(), "數(shù)據(jù)寫入失敗", Toast.LENGTH_SHORT).show();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? btnread.setOnClickListener(new View.OnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v) {
? ? ? ? ? ? ? ? String detail = "";
? ? ? ? ? ? ? ? FileHelper fHelper2 = new FileHelper(getApplicationContext());
? ? ? ? ? ? ? ? String fname = editname.getText().toString();
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? detail = fHelper2.readFromSD(fname);
? ? ? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? Toast.makeText(getApplicationContext(), detail, Toast.LENGTH_SHORT).show();
? ? ? ? ? ? }
? ? ? ? });
? ? }
}
```
其中FileHelper的代碼如下:
```java
package com.example.demo;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Author godv
* Date on 2020/4/14? 22:13
*/
public class FileHelper {
? ? private Context mContext;
? ? public FileHelper() {
? ? }
? ? public FileHelper(Context mContext) {
? ? ? ? super();
? ? ? ? this.mContext = mContext;
? ? }
? ? /**
? ? * @param filename
? ? * @param fileContent
? ? * @throws Exception
? ? */
? ? public void savFileToSD(String filename, String fileContent) throws Exception {
? ? ? ? //如果手機已插入sd卡,且app具有讀寫sd卡的權(quán)限
? ? ? ? if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
? ? ? ? ? ? filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
? ? ? ? ? ? File file=new File(filename);
? ? ? ? ? ? FileOutputStream output = new FileOutputStream(file);
? ? ? ? ? ? output.write(fileContent.getBytes());
? ? ? ? ? ? //將String字符串以字節(jié)流的形式寫入到輸出流中
? ? ? ? ? ? output.close();
? ? ? ? ? ? //關(guān)閉輸出流
? ? ? ? } else{
? ? ? ? ? ? Toast.makeText(mContext, "SD卡不存在或者不可讀寫", Toast.LENGTH_SHORT).show();
? ? ? ? }
? ? }
? ? //讀取SD卡中文件的方法
? ? //定義讀取文件的方法:
? ? public String readFromSD(String filename) throws IOException {
? ? ? ? StringBuilder sb = new StringBuilder("");
? ? ? ? if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
? ? ? ? ? ? filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
? ? ? ? ? ? //打開文件輸入流
? ? ? ? ? ? File file=new File(filename);
? ? ? ? ? ? FileInputStream input = new FileInputStream(file);
? ? ? ? ? ? byte[] temp = new byte[1024];
? ? ? ? ? ? int len = 0;
? ? ? ? ? ? //讀取文件內(nèi)容:
? ? ? ? ? ? while ((len = input.read(temp)) > 0) {
? ? ? ? ? ? ? ? sb.append(new String(temp, 0, len));
? ? ? ? ? ? }
? ? ? ? ? ? //關(guān)閉輸入流
? ? ? ? ? ? input.close();
? ? ? ? }
? ? ? ? return sb.toString();
? ? }
}
```
但是在android 6+后操作SD卡有動態(tài)權(quán)限問題。我們需要在Android中添加動態(tài)權(quán)限 也就是上述activity中的verifyStoragePermissions方法床未。當(dāng)然在Androidmanifast中配置也是必不可少的竭翠。
<!--? ? sd讀寫權(quán)限-->
? ? <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
? ? <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
但是問題還是沒有解決。在我們獲取操作流的時候薇搁。
FileOutputStream output = new FileOutputStream(file);
還是會出現(xiàn)報錯斋扰。
出現(xiàn)報錯的原因是由于android 10中文件讀寫新特性。還需要在Androidmanifast的application節(jié)點中加入android:requestLegacyExternalStorage="true"啃洋。最后問題得到解決传货。
參考文檔: