我有「聽」來打開文本文件的活動,這意味着清單:Android的閱讀活動的文本文件,濾波器打開文本文件
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
</intent-filter>
所以我瀏覽到文件瀏覽器,找到一些文本文件,嘗試打開它,並按預期方式將此活動存在於可用應用程序的列表中以完成操作。當活動啓動時,我知道活動獲得了正確的文件名,但它將文件視爲空(不會將內容打印到日誌中)。
備註:該文件不是空的,其他應用可以讀取他,文件路徑不包含空格,沒有例外或崩潰。
我在做什麼錯在這裏?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
//Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_VIEW.equals(action) && type != null && "text/plain".equals(type)) {
handleViewText(intent); //Handle text being sent
}
}
private void handleViewText(Intent intent) {
Uri uri = intent.getData();
//uri.getPath().toString(): /storage/emulated/0/dir/subDir/fileName.txt
BufferedReader br = null;
try {
String sCurrentLine;
InputStream is = getContentResolver().openInputStream(uri);
br = new BufferedReader(new InputStreamReader(is));
//This is also not working: br = new BufferedReader(new FileReader(uri.getPath()));
while ((sCurrentLine = br.readLine()) != null) {
Log.e("TAG", sCurrentLine); //never enters here
}
} catch (Exception e) {
//nothing
} finally {
try {
if (br != null) br.close();
} catch (Exception e) {
//nothing
}
}
}
第一件事第一,加上'e.printStackTrace()'到catch塊,檢查是否有異常是拋出。 – Blackbelt
@Blackbelt正如我在問題中提到的那樣,它沒有異常拋出它的測試,並且異常處理代碼被省略以僅用相關代碼的可讀問題。 – michael