2016年12月4日日曜日

android:intentからファイラーアプリ起動でファイル選択

Androidにはファイル選択ダイアログがないのでWeb上をうろついていた時にいいものに遭遇した。


これを参考に一部修正してみだ。












下記を発すると左図のように端末内のファイラーアプリがすべて呼び出される。
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, Utility.CHOSE_FILE_CODE);

この中から利用したいファイラーを選択するとそのファイラーが起動する。

選択したファイルのファイルパスを取得するには下記で受け取る。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
  if (requestCode == Utility.CHOSE_FILE_CODE && resultCode == RESULT_OK) {
   String filePath = data.getDataString();
   //storage以降を返す
   filePath=filePath.substring(filePath.indexOf("storage"));
   String decodedfilePath = URLDecoder.decode(filePath, "utf-8");
   Utility.filename=decodedfilePath;
   if(Utility.filename.indexOf("laptime.txt")>-1){
    Toast.makeText(this, Utility.filename, Toast.LENGTH_SHORT).show();
    Utility.dispsave(this,true);
    Utility.dispload(this);
    Utility.readList(this,true);
    }
   else Utility.msgToast(this,"No laptime.txt","laptime.txt でない!");
  }
} catch (UnsupportedEncodingException e) {}

このときファイラーによって下記のようにファイパスの先頭赤字部分のような独自のパスが付加されるので、それを取り除く必要がある。
・OIファイルマネージ:
content://org.openintents.filemanager/storega/emulated/0/laptimegpx.txt

・ファイルマネージャー
file:///storega/emulated/0/laptimegpx.txt

・AndroXplorer
file:///storega/emulated/0/laptimegpx.txt

・ESファイルエクスプローラ
content://com.estrongs.files/storega/emulated/0/laptimegpx.txt

ここでは"storage"以降を取得する。

このルールに該当しないファイラーは使えないのだ!