2014-07-20 32 views
2

我認爲這是非常簡單的事情,但它給了我比整個應用程序的其餘部分更多的工作。在卡上打開文件夾

我只想要一個按鈕來打開我的應用程序的「已下載的文件」文件夾。就這樣。沒有文件選擇器,沒有什麼複雜的。所有按鈕所需做的就是用默認應用程序打開文件夾(如果沒有默認應用程序,則打開應用程序選擇器)。

我嘗試了不同的解決方案,我在StackOverflow上看到這裏,但似乎沒有爲我工作。

例1:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/MyDownloadedFiles/"); 
intent.setDataAndType(uri, "text/plain"); 
startActivity(Intent.createChooser(intent, getString(R.string.action_downloaded))); 

在我的Android 4.4系統,這將打開奇巧文件選擇器,甚至不希望我的文件夾中打開...這似乎是默認爲卡根。但我確定該文件夾存在,並且提供給Intent的路徑確實是正確的。

例2:

Intent intent = new Intent(Intent.ACTION_VIEW); 
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/MyDownloadedFiles/"); 
intent.setDataAndType(uri, "text/plain"); 
startActivity(Intent.createChooser(intent, getString(R.string.action_downloaded))); 

這一個打開一些空白的活動有一個彈出說:「獲取文件內容時發生錯誤:MyDownloadedFiles」。

我該如何讓我的應用程序只是簡單地有一個文件夾放入內容的快捷方式?

回答

4

哇..最後!在我嘗試了很多事情之後,唯一的辦法就是將URI字符串包裝成一個文件,然後做一個Uri.fromFile:

File file = new File(Environment.getExternalStorageDirectory().getPath() + "/MyDownloadedFiles/"); 
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.fromFile(file), "*/*"); 
startActivity(Intent.createChooser(intent, getString(R.string.action_downloaded))); 
+0

那麼,該轉換(聲音真的很奇怪)和'「*/*」'的組合是關鍵嗎?不是''*/*'單獨嗎?或者也許是單獨的轉換? –

+0

我認爲這裏的關鍵是File對象可能會預先加入「file://」或其他內容,這使得它可以工作。「*/*」是不是肯定的解決方案,因爲如果我在類型中使用「Uri.parse()」和「*/*」,它將不起作用 - 將執行與上述示例1相同的操作。 – Nuno

+0

很奇怪我保持「不寫」星號(*)......無論如何,如果kitkat要求這樣做,如果你記住'Environment.getExternalStorageDirectory()'已經獲得了,你可以簡化代碼你一個File對象(更好的保持它簡單,所以我們不會創建一個從File到String到File到Uri:P的神話)恭喜! –

2

我覺得這個人能爲你工作:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() 
    + "/yourFolder/"); 
intent.setDataAndType(uri, "*/*"); 
startActivity(Intent.createChooser(intent, "Open /sdcard/yourFolder")); 
+0

你好。我已經嘗試過了,它和我的例子1非常相似。唯一的區別是類型。我在用text/plain去之前用*/*試過。 – Nuno

+0

此代碼有效! :) – dira