欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android 8.0 API 24.0 以上版本对SD卡的读写权限无效的问题

程序员文章站 2022-03-23 11:12:00
与Android 5.0不同,除了要在AndroidManifest.xml中设置读写权限外:还要在java代码中申请相关权限。Android6.0以后都要有动态申请权限。参考快速...

与Android 5.0不同,除了要在AndroidManifest.xml中设置读写权限外:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

还要在java代码中申请相关权限。Android6.0以后都要有动态申请权限。
参考快速解决设置Android 23.0以上版本对SD卡的读写权限无效的问题这篇博客,我在MainActivity.java中写了一个公共类,并在SDCardDemoActivity.java中进行授权调用。Android不同版本的Java代码弃用更改的比较频繁,我根据AS的提示做了一些修改。

package com.narziss.qqlogindemo2;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import static android.Manifest.permission;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private EditText mAccountText;
    private EditText mPasswordText;
    private Button mLogin;

    public static class permisionUtils {

        // Storage Permissions
        private static final int REQUEST_EXTERNAL_STORAGE = 1;
        private static String[] PERMISSIONS_STORAGE = {permission.READ_EXTERNAL_STORAGE,
                permission.WRITE_EXTERNAL_STORAGE};

        /**
         * Checks if the app has permission to write to device storage
         * If the app does not has permission then the user will be prompted to
         * grant permissions
         *
         * @param activity
         */
        public static void verifyStoragePermissions(Activity activity) {
            // Check if we have write permission
            int permission = ActivityCompat.checkSelfPermission(activity,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);

            if (permission != PackageManager.PERMISSION_GRANTED) {
                // We don't have permission so prompt the user
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                        REQUEST_EXTERNAL_STORAGE);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        initListener();

    }

    private void initListener() {
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: 点击了登录按钮...");
                handlerLoginEvent(v);
            }
        });
    }

    /**
     * 打开info.text文件,使其可见
     */
    @Override
    protected void onResume() {
        super.onResume();
//        File fileDir = this.getFilesDir();
//        File saveFile = new File(fileDir, "info.text");

        try {
            FileInputStream fileInputStream = this.openFileInput("info.text");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            String info = bufferedReader.readLine();

//            fos.write((accountText + "***" + passwordText).getBytes());
            String[] splits = info.split("\\*\\*\\*");
            String account = splits[0];
            String password = splits[1];

            mAccountText.setText(account);
            mPasswordText.setText(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理登录事件
     *
     * @param v
     */
    private void handlerLoginEvent(View v) {

        String accountText = mAccountText.getText().toString();
        //getText()返回值是Editable(可编辑)所以要toString()
        String passwordText = mPasswordText.getText().toString();

        //对账号密码进行检查,判空
//        if (accountText.length() == 0) {
//            Toast.makeText(this, "账号不可以为空..", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        if (passwordText.length() == 0) {
//            Toast.makeText(this, "密码不可以为空..", Toast.LENGTH_SHORT).show();
//        }

        if (TextUtils.isEmpty(accountText)) {
            Toast.makeText(this, "账号不能为空..", Toast.LENGTH_SHORT).show();
        }
        if (TextUtils.isEmpty(passwordText)) {
            Toast.makeText(this, "密码不能为空..", Toast.LENGTH_SHORT).show();
        }

        saveUserInfo(accountText, passwordText);
    }

    private void saveUserInfo(String accountText, String passwordText) {
        Log.d(TAG, "saveUserInfo: 保存用户信息...");

        File cacheDir = this.getCacheDir();
        Log.d(TAG, "cache dir ==  " + cacheDir.toString());

        File filesDir = this.getFilesDir();
        File saveFile = new File(filesDir, "info.text");
        Log.d(TAG, "files dir == " + filesDir.toString());

//        File file = new File("/data/data/com.narziss.qqlogindemo2/info.text");
        try {
            if (!saveFile.exists()) {
                saveFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(saveFile);
            fos.write((accountText + "***" + passwordText).getBytes());

            fos.close();
            Toast.makeText(this, "数据保存成功...", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void initView() {
        mAccountText = this.findViewById(R.id.et_account);
        mPasswordText = this.findViewById(R.id.et_password);
        mLogin = this.findViewById(R.id.bt_login);

    }
}
package com.narziss.qqlogindemo2;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.FileOutputStream;

import androidx.annotation.Nullable;

public class SDCardDemoActivity extends Activity implements View.OnClickListener {

    private Button mWriteDataBtn;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_sd_card);
        mWriteDataBtn = this.findViewById(R.id.write_data_to_sd_btn);
        mWriteDataBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        MainActivity.permisionUtils.verifyStoragePermissions(this);
        if (v == mWriteDataBtn) {
            File filepath = new File("/storage/self/primary");
            File file = new File(filepath, "info.txt");

            try {
                //检测读写权限

                FileOutputStream fos = new FileOutputStream(file);
                fos.write("com.narziss.com".getBytes());
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}

同时也参考了Android学习之请求外部存储sd卡读写权限(适配Android8.0以上包含Android10.0)少花时间少踩坑!这篇博客的内容

本文地址:https://blog.csdn.net/weixin_44145648/article/details/109647821

相关标签: Android