google在android4.4封闭了操作外置sd卡的功能,业界一片吐槽,so,在android5.0提供了全新的方式去操作外置sdcard。
1.首先获得外置sdcard的路径:
extSdcardPath = System. getenv( "SECONDARY_STORAGE");
2.获取uri,防止重复进入documentui界面
if (!TextUtils. isEmpty( extSdcardPath)) {
String strUri = PreferenceManager. getDefaultSharedPreferences( this).getString( PREF_DEFAULT_URI, null);
if (TextUtils. isEmpty(strUri)) {
if (Build.VERSION. SDK_INT >= 19) {
Intent intent = new Intent(Intent. ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, DOCUMENT_TREE_REQUEST);
}
} else {
Uri uri = Uri. parse(strUri);
DocumentFile rootDocumentFile = DocumentFile. fromTreeUri( this, uri);
createFile(rootDocumentFile);
}
}
3.处理返回结果
if (requestCode == DOCUMENT_TREE_REQUEST && resultCode == RESULT_OK) {
Uri uri = data.getData();
final int takeFlags = data.getFlags() & (Intent. FLAG_GRANT_READ_URI_PERMISSION | Intent. FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(uri, Intent. FLAG_GRANT_READ_URI_PERMISSION | Intent. FLAG_GRANT_WRITE_URI_PERMISSION);
PreferenceManager. getDefaultSharedPreferences( this).edit().putString( PREF_DEFAULT_URI, uri.toString()).commit();
DocumentFile documentFile = DocumentFile. fromTreeUri( this, uri);
for (DocumentFile file : documentFile.listFiles()) {
Log. d( TAG, "Found file " + file.getName() + " with size " + file.length());
}
createFile(documentFile);
} else {
Toast. makeText(getBaseContext(), "nonono", Toast. LENGTH_SHORT).show();
}
============================================================================================
全部代码
package com.bowen.sdddemo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.provider.DocumentFile;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import static android.R.id. list;
public class MainActivity extends AppCompatActivity {
private static int DOCUMENT_TREE_REQUEST = 1;
public static String ACTION_OPEN_DOCUMENT_TREE_URL = "ACTION_OPEN_DOCUMENT_TREE";
public String extSdcardPath = null;
public Button extSdcardBtn;
final static String PREF_DEFAULT_URI = "pref_default_uri";
List<FileItem> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
extSdcardBtn = (Button) findViewById(R.id. button);
extSdcardPath = System. getenv( "SECONDARY_STORAGE");
if (TextUtils. isEmpty( extSdcardPath)) {
extSdcardBtn.setVisibility(View. GONE);
} else {
extSdcardBtn.setText( extSdcardPath);
}
}
public void click(View view) {
if (!TextUtils. isEmpty( extSdcardPath)) {
String strUri = PreferenceManager. getDefaultSharedPreferences( this).getString( PREF_DEFAULT_URI, null);
if (TextUtils. isEmpty(strUri)) {
if (Build.VERSION. SDK_INT >= 19) {
Intent intent = new Intent(Intent. ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, DOCUMENT_TREE_REQUEST);
}
} else {
Uri uri = Uri. parse(strUri);
DocumentFile rootDocumentFile = DocumentFile. fromTreeUri( this, uri);
createFile(rootDocumentFile);
}
}
}
private void createFile(DocumentFile documentFile) {
DocumentFile newFile = documentFile.createFile( "text/plain", "M...y Novel");
OutputStream out = null;
try {
out = getContentResolver().openOutputStream(newFile.getUri());
out.write( "A long time ago...".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
String TAG = "Stttttttx";
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == DOCUMENT_TREE_REQUEST && resultCode == RESULT_OK) {
Uri uri = data.getData();
final int takeFlags = data.getFlags() & (Intent. FLAG_GRANT_READ_URI_PERMISSION | Intent. FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(uri, Intent. FLAG_GRANT_READ_URI_PERMISSION | Intent. FLAG_GRANT_WRITE_URI_PERMISSION);
PreferenceManager. getDefaultSharedPreferences( this).edit().putString( PREF_DEFAULT_URI, uri.toString()).commit();
DocumentFile documentFile = DocumentFile. fromTreeUri( this, uri);
for (DocumentFile file : documentFile.listFiles()) {
Log. d( TAG, "Found file " + file.getName() + " with size " + file.length());
}
createFile(documentFile);
} else {
Toast. makeText(getBaseContext(), "nonono", Toast. LENGTH_SHORT).show();
}
}
public void root(View view) {
boolean b = upgradeRootPermission(getPackageCodePath());
if (b) {
Toast. makeText(getBaseContext(), "rootle ", Toast. LENGTH_SHORT).show();
} else {
Toast. makeText(getBaseContext(), "mei 没 toor ", Toast. LENGTH_SHORT).show();
}
}
public static boolean upgradeRootPermission(String pkgCodePath) {
Process process = null;
DataOutputStream os = null;
try {
String cmd = "chmod 777 " + pkgCodePath;
process = Runtime. getRuntime().exec( "su"); // 切换到 root 帐号
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd + " \n ");
os.writeBytes( "exit \n ");
os.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
return true;
}
}
1.首先获得外置sdcard的路径:
extSdcardPath = System. getenv( "SECONDARY_STORAGE");
2.获取uri,防止重复进入documentui界面
if (!TextUtils. isEmpty( extSdcardPath)) {
String strUri = PreferenceManager. getDefaultSharedPreferences( this).getString( PREF_DEFAULT_URI, null);
if (TextUtils. isEmpty(strUri)) {
if (Build.VERSION. SDK_INT >= 19) {
Intent intent = new Intent(Intent. ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, DOCUMENT_TREE_REQUEST);
}
} else {
Uri uri = Uri. parse(strUri);
DocumentFile rootDocumentFile = DocumentFile. fromTreeUri( this, uri);
createFile(rootDocumentFile);
}
}
3.处理返回结果
if (requestCode == DOCUMENT_TREE_REQUEST && resultCode == RESULT_OK) {
Uri uri = data.getData();
final int takeFlags = data.getFlags() & (Intent. FLAG_GRANT_READ_URI_PERMISSION | Intent. FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(uri, Intent. FLAG_GRANT_READ_URI_PERMISSION | Intent. FLAG_GRANT_WRITE_URI_PERMISSION);
PreferenceManager. getDefaultSharedPreferences( this).edit().putString( PREF_DEFAULT_URI, uri.toString()).commit();
DocumentFile documentFile = DocumentFile. fromTreeUri( this, uri);
for (DocumentFile file : documentFile.listFiles()) {
Log. d( TAG, "Found file " + file.getName() + " with size " + file.length());
}
createFile(documentFile);
} else {
Toast. makeText(getBaseContext(), "nonono", Toast. LENGTH_SHORT).show();
}
============================================================================================
全部代码
package com.bowen.sdddemo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.provider.DocumentFile;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import static android.R.id. list;
public class MainActivity extends AppCompatActivity {
private static int DOCUMENT_TREE_REQUEST = 1;
public static String ACTION_OPEN_DOCUMENT_TREE_URL = "ACTION_OPEN_DOCUMENT_TREE";
public String extSdcardPath = null;
public Button extSdcardBtn;
final static String PREF_DEFAULT_URI = "pref_default_uri";
List<FileItem> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
extSdcardBtn = (Button) findViewById(R.id. button);
extSdcardPath = System. getenv( "SECONDARY_STORAGE");
if (TextUtils. isEmpty( extSdcardPath)) {
extSdcardBtn.setVisibility(View. GONE);
} else {
extSdcardBtn.setText( extSdcardPath);
}
}
public void click(View view) {
if (!TextUtils. isEmpty( extSdcardPath)) {
String strUri = PreferenceManager. getDefaultSharedPreferences( this).getString( PREF_DEFAULT_URI, null);
if (TextUtils. isEmpty(strUri)) {
if (Build.VERSION. SDK_INT >= 19) {
Intent intent = new Intent(Intent. ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, DOCUMENT_TREE_REQUEST);
}
} else {
Uri uri = Uri. parse(strUri);
DocumentFile rootDocumentFile = DocumentFile. fromTreeUri( this, uri);
createFile(rootDocumentFile);
}
}
}
private void createFile(DocumentFile documentFile) {
DocumentFile newFile = documentFile.createFile( "text/plain", "M...y Novel");
OutputStream out = null;
try {
out = getContentResolver().openOutputStream(newFile.getUri());
out.write( "A long time ago...".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
String TAG = "Stttttttx";
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == DOCUMENT_TREE_REQUEST && resultCode == RESULT_OK) {
Uri uri = data.getData();
final int takeFlags = data.getFlags() & (Intent. FLAG_GRANT_READ_URI_PERMISSION | Intent. FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(uri, Intent. FLAG_GRANT_READ_URI_PERMISSION | Intent. FLAG_GRANT_WRITE_URI_PERMISSION);
PreferenceManager. getDefaultSharedPreferences( this).edit().putString( PREF_DEFAULT_URI, uri.toString()).commit();
DocumentFile documentFile = DocumentFile. fromTreeUri( this, uri);
for (DocumentFile file : documentFile.listFiles()) {
Log. d( TAG, "Found file " + file.getName() + " with size " + file.length());
}
createFile(documentFile);
} else {
Toast. makeText(getBaseContext(), "nonono", Toast. LENGTH_SHORT).show();
}
}
public void root(View view) {
boolean b = upgradeRootPermission(getPackageCodePath());
if (b) {
Toast. makeText(getBaseContext(), "rootle ", Toast. LENGTH_SHORT).show();
} else {
Toast. makeText(getBaseContext(), "mei 没 toor ", Toast. LENGTH_SHORT).show();
}
}
public static boolean upgradeRootPermission(String pkgCodePath) {
Process process = null;
DataOutputStream os = null;
try {
String cmd = "chmod 777 " + pkgCodePath;
process = Runtime. getRuntime().exec( "su"); // 切换到 root 帐号
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd + " \n ");
os.writeBytes( "exit \n ");
os.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
return true;
}
}