2016-01-21 51 views
0

我在我的應用程序中有幾張圖片,當用戶點擊它們時,我想在默認查看器中打開它們。這裏是我的代碼:Android意圖打開圖片庫,但不是圖片。爲什麼?

Intent intent = new Intent(Intent.ACTION_VIEW); 
Uri uri = Uri.parse("file://" + Environment.getExternalStorageDirectory().toString() + "/Pictures/mypic.jpg"); 
intent.setData(uri); 
intent.setType("image/jpeg"); 

startActivity(intent); 

默認瀏覽器確實是打開的,但它顯示了它的「絲網之鄉」,顯示所有文件夾和畫廊。它不顯示選定的圖片。

我在做什麼錯?

+0

'我在我的應用程序中有幾張照片。在你的應用程序?哪裏?請首先解釋您的圖片的確切位置。 – greenapps

+0

'默認查看器'???什麼是默認查看器? – greenapps

+0

@greenapps圖像完全位於'/ storage/emulated/0 /圖片/'我確信我使用的路徑是正確的,並且圖像存在。 _default viewer_是用戶配置的任何一個。它可以是圖庫,QuickPic或其他。系統應該知道哪一個可以使用。 – ilvidel

回答

1

將下面的代碼放置在try塊中,您可以打開任何文件: 添加catch塊自己。

   String FileName = ...full path of file... 

      MimeTypeMap map = MimeTypeMap.getSingleton(); 
      String extension = map.getFileExtensionFromUrl(FileName.toLowerCase().replace(" ", "")); // does not work with spaces in filename 

      String mimetype = map.getMimeTypeFromExtension(extension); 

      Toast.makeText(context, FileName + "\nMimeType: " + mimetype + "\nExtension: " + extension , Toast.LENGTH_SHORT).show(); 

      if (mimetype == null) 
       { 
       mimetype = "text/plain"; 
       Toast.makeText(context, "MimeType: " + mimetype, Toast.LENGTH_SHORT).show(); 
       } 



      String Url = "file://" + FileName; 

      Intent intent = new Intent(Intent.ACTION_VIEW); 
      intent.setDataAndType(Uri.parse(Url), mimetype);  
      context.startActivity(intent);    
+1

嗯,我沒有看過你的代碼太多,突然間我看到你有相同的。你的代碼唯一的問題是你同時使用setData()和setType()。 setTyp()會撤消setData()設置的數據。所以這就是爲什麼它不起作用。 – greenapps

+0

這正是問題所在,先生。 'setType()'和'setData()'的順序以及它們的單獨使用而不是'setDataAndType()'以很好的方式影響結果。 – ilvidel