Android SD卡

Ida ·
更新时间:2024-09-21
· 644 次阅读

一、判断SD卡使用情况 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(MainActivity.this,"SD卡准备就绪!",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this,"SD卡不存在或者未挂载!",Toast.LENGTH_SHORT).show(); } 二、获取SD卡的储存情况 File ext=Environment.getExternalStorageDirectory(); long usableSpace=ext.getUsableSpace(); long totalSpace=ext.getTotalSpace(); String usableSize= Formatter.formatFileSize(MainActivity.this,usableSpace); String totalSize=Formatter.formatFileSize(MainActivity.this,totalSpace); Toast.makeText(MainActivity.this,"usableSize:"+usableSize+"--"+totalSize,Toast.LENGTH_SHORT).show(); 三、权限问题 //在AndroidManifest中添加SD卡读写的权限 //从Android6.0开始需要动态授权 Manifest.permission.READ_EXTERNAL_STORAGE Manifest.permission.WRITE_EXTERNAL_STORAGE 四、权限申请 //动态申请权限方法 private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE" }; public static void verifyStoragePermissions(Activity activity) { try { //检测是否有写的权限 int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.WRITE_EXTERNAL_STORAGE"); if (permission != PackageManager.PERMISSION_GRANTED) { // 没有写的权限,去申请写的权限,会弹出对话框 ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE); } } catch (Exception e) { e.printStackTrace(); } } 五、写入数据  File f2=new File(ext,"test.data"); try { verifyStoragePermissions(MainActivity.this); OutputStream out=new FileOutputStream(f2); out.write("test".getBytes()); out.close(); } catch (Exception e) { e.printStackTrace(); }  六、读取数据 try { InputStream in=new FileInputStream(f2); byte[] buffer=new byte[64]; int len=in.read(buffer); String str=new String(buffer,0,len); } catch (Exception e) { e.printStackTrace(); }
作者:大亮



sd sd卡 Android

需要 登录 后方可回复, 如果你还没有账号请 注册新账号