Android 10 中讀寫SD卡權(quán)限的問題

記一次在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"啃洋。最后問題得到解決传货。

參考文檔:

適配策略

解決方案

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市宏娄,隨后出現(xiàn)的幾起案子问裕,更是在濱河造成了極大的恐慌,老刑警劉巖孵坚,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件粮宛,死亡現(xiàn)場離奇詭異,居然都是意外死亡卖宠,警方通過查閱死者的電腦和手機窟勃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來逗堵,“玉大人秉氧,你說我怎么就攤上這事⊙殉樱” “怎么了汁咏?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長作媚。 經(jīng)常有香客問我攘滩,道長,這世上最難降的妖魔是什么纸泡? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任漂问,我火速辦了婚禮,結(jié)果婚禮上女揭,老公的妹妹穿的比我還像新娘蚤假。我一直安慰自己,他們只是感情好吧兔,可當(dāng)我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布磷仰。 她就那樣靜靜地躺著,像睡著了一般境蔼。 火紅的嫁衣襯著肌膚如雪灶平。 梳的紋絲不亂的頭發(fā)上伺通,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天,我揣著相機與錄音逢享,去河邊找鬼罐监。 笑死,一個胖子當(dāng)著我的面吹牛瞒爬,可吹牛的內(nèi)容都是我干的笑诅。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼疮鲫,長吁一口氣:“原來是場噩夢啊……” “哼吆你!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起俊犯,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤妇多,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后燕侠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體者祖,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年绢彤,在試婚紗的時候發(fā)現(xiàn)自己被綠了七问。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡茫舶,死狀恐怖械巡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情饶氏,我是刑警寧澤讥耗,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站疹启,受9級特大地震影響古程,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜喊崖,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一挣磨、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧荤懂,春花似錦茁裙、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽谣蠢。三九已至粟耻,卻和暖如春查近,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背挤忙。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工霜威, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人册烈。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓戈泼,卻偏偏與公主長得像,于是被迫代替她去往敵國和親赏僧。 傳聞我的和親對象是個殘疾皇子大猛,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內(nèi)容