Android高版本上读写sdcard

Manifest.xml

    <uses-permission
        android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
        tools:ignore="ProtectedPermissions" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
    <!--存储权限-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

Java代码

​

package com.study.example;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.PowerManager;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
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 androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private boolean havePermission = false;
    private EditText et_ip, et_port;
    //    private CheckBox ch_checkbox;
    private Button btn_save;
//    private SharedPreferencesUtils sharedPreferencesUtils;


    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        sharedPreferencesUtils = new SharedPreferencesUtils(this);

        et_ip = (EditText) findViewById(R.id.et_ip);
        et_port = (EditText) findViewById(R.id.et_port);
//        ch_checkbox = (CheckBox) findViewById(R.id.checkbox);
        btn_save = (Button) findViewById(R.id.btn_save);
        //添加点击事件
        btn_save.setOnClickListener(new onClick());


        //获取用户保存的信息
        //1.
        //String[] info = Utils.readInfo();
        //2.
        //String[] info = Utils.readInfoByContext(this);
        //3.
        String[] info = Utils.readInfo();
//        String IP = sharedPreferencesUtils.readConfig("ip");
//        String Port = sharedPreferencesUtils.readConfig("port");

        //判断是否为空,不为则显示用户名和密码
        if (info != null) {
            //显示用户上一次登录的信息
            et_ip.setText(info[0]);
            et_port.setText(info[1]);
        } else {
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        checkPermission();
    }

    private class onClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            System.out.println("hello world");
            String ip = et_ip.getText().toString().trim();
            String port = et_port.getText().toString().trim();
            //判断用户、密码输入是否为空
            if (TextUtils.isEmpty(ip)) {
                Toast.makeText(MainActivity.this, "IP不能为空噢", Toast.LENGTH_SHORT).show();
            } else if (TextUtils.isEmpty(port)) {
                Toast.makeText(MainActivity.this, "端口不能为空", Toast.LENGTH_SHORT).show();
            } else if (!Utils.ipCheck(ip)) {
                Toast.makeText(MainActivity.this, "IP不合法", Toast.LENGTH_SHORT).show();
            } else {
                //boolean saveInfo = Utils.saveInfoByContent(MainActivity.this,username,pwd);
                //3.需要添加访问sdcard的权限
                boolean saveInfo = Utils.saveInfo(ip, port);
//                boolean ipSave = sharedPreferencesUtils.saveConfig("ip", ip);
//                boolean portSave = sharedPreferencesUtils.saveConfig("port", port);
                if (saveInfo) {
                    Toast.makeText(MainActivity.this, "保存成功!", Toast.LENGTH_SHORT).show();
                    Log.d("MainActivity", "保存成功" + "\n");
                } else {
                    Toast.makeText(MainActivity.this, "保存失败!", Toast.LENGTH_SHORT).show();
                    Log.d("MainActivity", "保存失败" + "\n");
                }
            }
        }
    }

    private AlertDialog dialog;

    private void checkPermission() {
        //检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (Build.VERSION.SDK_INT >= 30) {
            if (!Environment.isExternalStorageManager()) {
                if (dialog != null) {
                    dialog.dismiss();
                    dialog = null;
                }
                dialog = new AlertDialog.Builder(this)
                        .setTitle("提示")//设置标题
                        .setMessage("请开启文件访问权限,否则无法正常使用本应用!")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                                startActivity(intent);
                            }
                        }).create();
                dialog.show();
            } else {
                havePermission = true;
                Log.i("swyLog", "Android 11以上,当前已有权限");
            }
        } else {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    if (dialog != null) {
                        dialog.dismiss();
                        dialog = null;
                    }
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("提示");
                    builder.setMessage("请开启文件访问权限,否则无法正常使用本应用!");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                        }
                    });//设置标题
                    dialog = builder.create();
                    dialog.show();
                } else {
                    havePermission = true;
                    Log.i("swyLog", "Android 6.0以上,11以下,当前已有权限");
                }
            } else {
                havePermission = true;
                Log.i("swyLog", "Android 6.0以下,已获取权限");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    havePermission = true;
                    Toast.makeText(this, "授权成功!", Toast.LENGTH_SHORT).show();
                } else {
                    havePermission = false;
                    Toast.makeText(this, "授权被拒绝!", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }
}

​
package com.study.example;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

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

public class Utils {
    /**
     * 1.
     * 通过file文件保存用户信息
     *
     * @param username 用户名
     * @param pwd      密码
     * @return
     */
    public static boolean saveInfo(String username, String pwd) {
        String info = username + "##" + pwd;
        String path = Environment.getExternalStorageDirectory() + "/info.txt";
        Log.d("MainActivity", path + "\n");
        File file = new File(path);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //将字符串写入到文件中
            fos.write(info.getBytes());
            //关闭数据流
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 1.
     * 读取保存再.txt文件中的用户名、密码
     *
     * @return
     */
    public static String[] readInfo() {
        String path = Environment.getExternalStorageDirectory() + "/info.txt";
        Log.d("MainActivity", path + "\n");

        File file = new File(path);

        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

            String temp = reader.readLine();
            String[] result = temp.split("##");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 2.
     * 通过context上下文的方式保存用户信息
     *
     * @param context  上下文
     * @param username 用户名
     * @param pwd      密码
     * @return
     */
    public static boolean saveInfoByContent(Context context, String username, String pwd) {
        String info = username + "##" + pwd;
        //2.1获取相关的私有路径
        //File file = new File(context.getFilesDir().getAbsolutePath()+"/info.txt");
        try {
            //2.1
            //FileOutputStream fos = new FileOutputStream(file);
            //2.2
            FileOutputStream fos = context.openFileOutput("info.txt", Context.MODE_PRIVATE);
            //将字符串写入到文件中
            fos.write(info.getBytes());
            //关闭数据流
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 2.
     * 通过上下文的方式读取保存在.txt文件中的用户名、密码
     *
     * @return
     */
    public static String[] readInfoByContext(Context context) {
        try {
            FileInputStream fis = context.openFileInput("info.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

            String temp = reader.readLine();
            String[] result = temp.split("##");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 3.
     * 保存在sdcard上
     *
     * @param username 用户名
     * @param pwd      密码
     * @return
     */
    public static boolean saveInfoSdcard(String username, String pwd) {
        String info = username + "##" + pwd;
        File file = new File("mnt/sdcard/info.txt");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //将字符串写入到文件中
            fos.write(info.getBytes());
            //关闭数据流
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 3.
     * 读取保存在SD卡.txt文件中的用户名、密码
     *
     * @return
     */
    public static String[] readInfoBySdcard() {
        //3.1 两种方式
        //File file =  new File("mnt/sdcard/info.txt");

        //3.2
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "mnt/sdcard/info.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            String temp = reader.readLine();
            String[] result = temp.split("##");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断IP地址的合法性,这里采用了正则表达式的方法来判断
     * return true,合法
     */
    public static boolean ipCheck(String text) {
        if (text != null && !text.isEmpty()) {
            // 定义正则表达式
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判断ip地址是否与正则表达式匹配
            if (text.matches(regex)) {
                // 返回判断信息
                return true;
            } else {
                // 返回判断信息
                return false;
            }
        }
        return false;
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值