public class Sd_manager extends Activity {
public static final int REQUEST_CODE_SECONDARY_STORAGE_ACCESS_PERMISSION = 2;
private Button button01;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sd_manager);
button01 = (Button) findViewById(R.id.button1);//編集モード
//
//編集モードリスナー
//
button01.setOnClickListener(new View.OnClickListener() {//イベントリスナーの設定「計算」
@Override
public void onClick(View view) {//viewの意味がわからない
// TODO 自動生成されたメソッド・スタブ
//
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_CODE_SECONDARY_STORAGE_ACCESS_PERMISSION);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_SECONDARY_STORAGE_ACCESS_PERMISSION:
// 取得した URI に恒久的にアクセスできるようにするための処理
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContentResolver().takePersistableUriPermission(data.getData(),
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
Uri treeUri = data.getData();
//ここでtreeUriの実際のパスを取得したい
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
// Create a new file and write into it
DocumentFile newFile = pickedDir.createFile("text", "My Novel");
OutputStream out;
try {
out = getContentResolver().openOutputStream(newFile.getUri());
out.write("A long time ago...".getBytes());
out.close();
} catch (FileNotFoundException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
break;
}
}
}