Explanation of the Application Example of android 6.0 Writing into SD Card

  • 2021-10-11 19:32:58
  • OfStack

Mobile phones in 6.0 need to apply for permission to write mobile phones

I did the following

I post the code below


package com.example.admin.sdapplication;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

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

public class SdkActivity extends AppCompatActivity implements View.OnClickListener{
 private Button btn_write;
 private Button btn_read;
 final int REQUEST_WRITE=1;// Request code for permission application 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_sdk);

  btn_write= (Button) findViewById(R.id.btn_write);
  btn_read= (Button) findViewById(R.id.btn_read);
  btn_read.setOnClickListener(this);
  btn_write.setOnClickListener(this);
 }

 private void showAlert(){
  Dialog alertDialog = new AlertDialog.Builder(this).
    setTitle(" Permission description ").
    setMessage(" We need this permission to provide you with storage services ").
    setIcon(R.drawable.ic_launcher).
    setPositiveButton(" Determine ", new DialogInterface.OnClickListener() {

     @Override
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      //2 Apply for authority :  Parameter 2 An array of permissions; Parameter 3 Request code 
      ActivityCompat.requestPermissions(SdkActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE);
     }
    }).
    setNegativeButton(" Cancel ", new DialogInterface.OnClickListener() {

     @Override
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
     }
    }).
    create();
  alertDialog.show();
 }
 @Override
 public void onClick(View view) {
  switch (view.getId()){
   case R.id.btn_read:
    String s= readToSdCard();
    Log.i("readTosdCard",s);
    break;
   case R.id.btn_write:
    // Judge whether 6.0 The above mobile phones   If you don't, you don't have to 
    if(Build.VERSION.SDK_INT>=23){
     // Determine if you have this permission 
     if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
      // No. 1 1 Judgment that the request permission is cancelled, 1 You can not write 
      if (ActivityCompat.shouldShowRequestPermissionRationale(SdkActivity.this,
        Manifest.permission.WRITE_EXTERNAL_STORAGE)){
       Log.i("readTosdCard"," We need this permission to provide you with storage services ");
       showAlert();
      }else {
       //2 Apply for authority :  Parameter 2 An array of permissions; Parameter 3 Request code 
       ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE);
      }
     }else {
      writeToSdCard();
     }
    } else{
     writeToSdCard();
    }
    break;
  }
 }

 // Write data 
 public void writeToSdCard(){
  //1 , judgment sd Is the card available 
  if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
   //sd Card available 
   //2 , get the sd Card path 
   File sdFile=Environment.getExternalStorageDirectory();
   File path=new File(sdFile,"a.txt");//sd Under the card a.txt Documents   Parameter   Front   Is a directory   Followed by files 
   try {
    FileOutputStream fileOutputStream=new FileOutputStream(path);
    fileOutputStream.write("hello".getBytes());
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
 // Read data 
 public String readToSdCard(){
  StringBuilder stringBuilder = null;
  if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
   File sdFile=Environment.getExternalStorageDirectory();
   File path=new File(sdFile,"a.txt");
   stringBuilder =new StringBuilder();
   try {
    FileInputStream fileInputStream=new FileInputStream(path);
    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(fileInputStream));

    String str;
    while ((str=bufferedReader.readLine())!=null){
     stringBuilder.append(str);
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return stringBuilder.toString();
 }
 // Method for judging authorization   Successful authorization calls the write method directly   This is a listening callback 
 // Parameter   Context   Array of authorization results   Array to apply for authorization 
 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  if(requestCode==REQUEST_WRITE&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
   writeToSdCard();
  }

 }
}

In fact, it is to judge whether the 6.0 mobile phone applies for permission again, and use the callback mechanism of applying for permission to call the write processing directly after the permission is applied

The comment is very clear. Just look at the code.

Another point that needs to be noted is that we also handled the first time that the user refused permission, and when the second time that the user needed to request, the user was prompted for permission


// No. 1 1 Judgment that the request permission is cancelled, 1 You can not write 
if (ActivityCompat.shouldShowRequestPermissionRationale(SdkActivity.this,
  Manifest.permission.WRITE_EXTERNAL_STORAGE)){
 Log.i("readTosdCard"," We need this permission to provide you with storage services ");
 showAlert();
}else {
 //2 Apply for authority :  Parameter 2 An array of permissions; Parameter 3 Request code 
 ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE);
}

Related articles: