Shi*_*til 3 java android android-sdcard
Kit-Kat问题无法写入外部SD卡,
如 Goolge文档中所述 为了简化运行KITKAT或更早版本的设备上的代码,您可以使用fromFile(File)模拟DocumentsProvider的行为 下面的代码(New API)适用于Lollipop,但如何使用kitkat的新API?
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 42);
}
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode == RESULT_OK) {
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromFile(new File("/mnt/extSdCard/Test"));
// List all existing files inside picked directory
for (DocumentFile file : pickedDir.listFiles()) {
Log.d("Tag", "Found file " + file.getName() + " with size " + file.length());
}
// Create a new file and write into it
DocumentFile newFile = pickedDir.createFile("text/plain", "My Novel");
OutputStream out = null;
try {
out = getContentResolver().openOutputStream(newFile.getUri());
out.write("A long time ago...".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用fromFile(File)?
我试过但说 无法创建文件:java.io.IOException:打开失败:EACCES(权限被拒绝)
即使在添加权限uses-permission android:name ="android.permission.WRITE_EXTERNAL_STORAGE"之后
Android版本4.4.2
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
DocumentFile pickedDir = DocumentFile.fromFile(new File("/mnt/extSdCard/Test"));
// List all existing files inside picked directory
for (DocumentFile file : pickedDir.listFiles()) {
Log.d("Tag", "Found file " + file.getName() + " with size " + file.length());
}
// Create a new file and write into it
DocumentFile newFile = pickedDir.createFile("text/plain", "My Novel");
OutputStream out = null;
try {
//Says NullPointerException
out = getContentResolver().openOutputStream(newFile.getUri()); out.write("A long time ago...".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
新的API只能帮助Lollipop上的人写入二级SD卡,KitKat上的人仍然不走运.
除了您的应用程序已有的内容之外,这不会为您提供对基础文件的任何其他访问权限.
要利用Intent.ACTION_OPEN_DOCUMENT_TREE创建的新权限, 您必须使用DocumentFile.fromTreeUri返回的Uri.
| 归档时间: |
|
| 查看次数: |
2215 次 |
| 最近记录: |