Dodge Through Obstacles! Explore New Locations! Reach Your Destiny! PLAY NOW !!
If you are here reading this, you might have already gone though most of the Stack-Overflow pages relating to this post. Trust me i have too gone through them when i first faced this issue. That is the reason why i thought of make an entire article on this headache. If you have gone through at least one page of the Stack-Overflow, you might have noticed the way to open a specific file (probably a “pdf” file or a “jpeg” file). But what if you want to open a file which is not a standard file type? Maybe your Application specific saved files. This is the time when you really loose control or even get mad… LOL!. Analyse the code below first and i will explain it in detail.
String url=Environment.getExternalStorageDirectory().getAbsolutePath()+"/Saves/contacts.vcf"; File file = new File(url); Intent intent = new Intent(Intent.ACTION_VIEW); String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url)); intent.setDataAndType(Uri.fromFile(file), mimeType); Intent intent1 = Intent.createChooser(intent, "Open With"); startActivity(intent1);
In the code i have tried to open a V-Card file(contacts.vcf) from the “Saves/” folder inside my storage. When i execute this code, the system allows as to open the file with the available applications in the device.
In Line 1, the address of the file is stored inside a String variable “url“. In line 2, we create a File object with that address. In the Line 4, we ask the system to self determine the mimeType of the file that we need to open from the activity. In the next line we simply uses the returned mimeType to specify additional information to the Intent about the targeting file.
By following this you will be able to open any kind of file including mp3, doc, ppt, pdf, vcf, xml, apk from your currently running activity.
Read More :