2011-04-13 46 views
1

我試圖創建簡單地在SD卡上打開文件的程序。我試着打開mp3,mp4和apk--下面的代碼總是意外崩潰。關於「file://」的startActivity鏈接崩潰

String _path = "file:///sdcard/1.apk"; 

    Uri outputFileUri = Uri.parse(_path); 
    Intent intent = new Intent(); 
    intent.setAction(Intent.ACTION_VIEW); 

市場聯繫也崩潰。但是當我設置_path =「http://google.com」 - 瀏覽器正常打開。我怎樣才能使這個代碼工作?

回答

0

如果你想安裝的APK,您需要使用以下命令:

String fileName = Environment.getExternalStorageDirectory() + "/1.apk"; 
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive"); 
startActivity(intent); 

如果你想啓動的應用程序(安裝後),則:

Intent intent = new Intent(); 
intent.setClassName("com.pkg.addr", "com.pkg.addr.MainActivity"); 
startActivity(intent); 

如果您嘗試啓動播放器播放mp3文件:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW); 
Uri data = Uri.parse("file:///sdcard/1.mp3"); 
intent.setDataAndType(data,"audio/mp3"); 
startActivity(intent); 

希望有所幫助。

+0

太棒了!作品!謝謝! 所以我需要總是定義MIME類型?不要讓android讓用戶選擇他想對文件做什麼? – POMATu 2011-04-13 15:56:54

+0

Android確實允許用戶選擇哪個應用程序應該處理文件,在他手機上的那些能夠處理該文件的應用程序中。 – rajath 2011-04-13 16:06:45

+0

但是,當我沒有設置類型,應用程序崩潰。爲什麼android在類型未設置時不顯示標準的openfile對話框? – POMATu 2011-04-13 16:34:01