I have a list of files in listview .. these files actually reside on sd card. Now i want to open these files by using an app picker. I.e if this file is an image it should show all applications in my phone that can open jpg type files in application chooser box.
How can i do this .. can someone give me any idea about it?
Any help is appreciated :)
Thanks in advance
I found dis piece of code ..how can i use it in my application?
public class Redirector {
public static void showActivityWithChooser( Context context, int chooserLabelTitleId, Intent intent ) {
try {
context.startActivity( Intent.createChooser( intent,
context.getResources().getString( chooserLabelTitleId )) );
} catch( Exception e ) {
e.printStackTrace();
}
}
public static void viewInExternalApplication( Context context, String url ) {
Intent intent = new Intent( Intent.ACTION_VIEW );
intent.setData( Uri.parse( url ) );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET );
showActivityWithChooser( context, R.string.open_chooser_title, intent );
}
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/YOUR_PATH_TO_Images/";
try {
if (f.exists()) {
File file = new File(path
+ listViewArray.get(position).getImageName());
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),
"image/*");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent1 = Intent.createChooser(target,
"Open With");
startActivity(intent1);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No Pdf found",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Just send the intent. Android will show an app chosser itself, if more than one app capable of showing the specified file type is installed, or start the app directly, if there's just one (or the user selected "always"/"remember my choice" in the app chooser)
To get the applications that can successfully open a given intent you'll use the PackageManager. Simply construct the intent as above and then use this code to get the applications that can handle the intent.
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_VIEW);
myIntent.addCategory("android.intent.category.LAUNCHER");
myIntent.setType("mp3");
PackageManager manager = getPackageManager();
List<ResolveInfo> info = manager.queryIntentActivities(myIntent,PackageManager.MATCH_DEFAULT_ONLY);
This will give you all the information on the programs that can handle the intent, including icon, and packagename. You can then create a dialog box with these options and save the option the user chooses.
1.This is question is related to Mime type
First get extenstion of file and set type of mime used by element into list
private String extenstionFile(String url) {
if (url.indexOf("?")>-1) {
url = url.substring(0,url.indexOf("?"));
}
if (url.lastIndexOf(".") == -1) {
return null;
} else {
String ext = url.substring(url.lastIndexOf(".") );
if (ext.indexOf("%")>-1) {
ext = ext.substring(0,ext.indexOf("%"));
}
if (ext.indexOf("/")>-1) {
ext = ext.substring(0,ext.indexOf("/"));
}
return ext.toLowerCase();
}
}
Than open supported type of application list:-
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);
//Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(extenstionFile(getFile().toString()).substring(1));
newIntent.setDataAndType(Uri.fromFile(getFile()),mimeType);
newIntent.setFlags(newIntent.FLAG_ACTIVITY_NEW_TASK);
try {
_context.startActivity(newIntent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(_context, "No handler for this type of file.", 4000).show();
}
After selecting the file please check whic file is it (ex pdf , jpg) , After that create an ACTION_VIEW intent and set the type of intent according to selected file type. Now brocast the intent , System itself will show you the list of applications thats supports the viewing of yor file.
Check below link you will get better idea.
http://developer.android.com/guide/components/intents-filters.html
Related
My requirement is to download and view the Excel, Doc files in my app. So I downloaded the Excel/Doc file in phone storage and called the ACTION_VIEW Intent by passing the file path. Then I got this error saying "Try saving the file on the device and then opening it."
I can be glad if any one can suggest me another alternatives as well to open excel or doc files. Please guys i have searched a lot for this so far i didn't find the solution and i am sure that i have used proper intent for opening files.
Where My Code:
Intent intentpdf = new Intent(Intent.ACTION_VIEW);
intentpdf.setDataAndType(Uri.parse(message), "application/msword");
intentpdf.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
mactivity.startActivity(intentpdf);
} catch (ActivityNotFoundException e) {
if (!mactivity.isFinishing())
Toast.makeText(mactivity, "Install MSWord Viewer.", Toast.LENGTH_LONG).show();
}
Intent intentpdf = new Intent(Intent.ACTION_VIEW);
intentpdf.setDataAndType(Uri.parse(message), "application/vnd.ms-excel");
intentpdf.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
mactivity.startActivity(intentpdf);
} catch (ActivityNotFoundException e) {
if (!mactivity.isFinishing())
Toast.makeText(mactivity, "Install Excel Viewer.", Toast.LENGTH_LONG).show();
}
You need the flags FLAG_ACTIVITY_NO_HISTORY,FLAG_GRANT_READ_URI_PERMISSION, FLAG_GRANT_WRITE_URI_PERMISSION.
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION );
I had this exact same problem and I fixed it. The problem is most likely with your ContentProvider/FileProvider implementation. My Excel sheet opened fine in Google Sheets but I got this error in MS Excel. The fix was to return the proper content type (via the getType() method) out of your provider. Returning the wrong content type will cause the error.
Try this code to see if it helps...and if it does, you can fully implement the routine for files of all types.
#Override
public String getType(Uri uri) {
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
Good Luck!
Try get mime type from file
public String getMimeTypeByFile(String filePath) {
MimeTypeMap type = MimeTypeMap.getSingleton();
return type.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(filePath));
}
nothing is worked for me to open the Doc,PPT,Excel files with intent at last I find a better solution , please check the code here
if(fileType.equalsIgnoreCase("doc") || fileType.equalsIgnoreCase("docx")) {
String str = "com.microsoft.office.word";
Uri pathe = Uri.fromFile(fileN);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(pathe, "application/msword");
PackageManager packageManager = activity.getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
activity.startActivity(intent.createChooser(intent, "Choose app to open document"));
}
else
{
//Launch PlayStore
try {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+str)));
} catch (android.content.ActivityNotFoundException n) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id="+str)));
}
}
Here is the result : check the screenshot
[This question may be duplicate, but i din't find what i am looking for]
[Read]How can we open files like ppt, doc, pps, rtf, etc. in Android?
I am having PPT files. In my app, i have a list view which display the PPT file list available in my private app folder. In click of particular file, i want to open corresponding PPT file for reading in my App.
The App which i am creating is just like collection of PPTs and reading them one by one.
Please provide any API/Example/Links.
You need to use other application to open your ppt files , Make sure that file location you are providing is accessible to other application. Try with following :
final Uri uri = Uri.fromFile(file);
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
if(list.size() > 0)
startActivity(context, intent);
Available application will be shown to user and user can choose application which can open.
private void openPPT(final String path) {
File file = new File(path);
Uri uri ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/vnd.ms-powerpoint");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}
I know that I can let user view their PDF file like that
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
startActivity(intent);
But I was wondering, if I dont know the file type (could be an image, pdf, text ..etc). Is there away I can let the user open it (and android automatically detect the file type and show the list of possible programs)?
Thank you
Try this,
import android.webkit.MimeTypeMap;
try
{
Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
File file = new File(aFile.getAbsolutePath());
String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
myIntent.setDataAndType(Uri.fromFile(file), mimetype);
startActivity(myIntent);
}
catch (Exception e)
{
// TODO: handle exception
String data = e.getMessage();
}
I'm trying to implement "set as" functionality for images. I'm using Intent.ATTACH_DATA so users can at least choose contact photo and wallpaper. The extras I should pass confuse me. If I read the documentation right,
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setType("image/*");
intent.setData(mImageCaptureUri);
startActivity(Intent.createChooser(intent, "hey"));
Should be all. This works for wallpapers, but with megapixel data, the app crashes, because no crop activity could be found. Does someone have a working example? The official gallery app does manage to find the camera.crop activity...
A general hint on where to find elaborate system intent documentation is welcome as well.
After a long and winding road through the android source, I found the actual code in the default gallery (gallery3d) app. I adapted for use in my own application, and rewrote it again for convenience when importing in other applications. If you use or appreciate this, I ask that you upvote this answer.
Adapted from : gallery3d source at grepcode
Usage: change first line to match the full path (starting with /mnt/) of your photo.
add string "set_as" to your strings.xml as the action chooser title.
String absolutepath = MyApplication.appRootDir + relpath;//change for your application
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = absolutepath.substring(absolutepath.lastIndexOf('.') + 1);
String mimeType = map.getMimeTypeFromExtension(ext);
Uri uri = Uri.fromFile(new File(absolutepath));
intent.setDataAndType(uri, mimeType);
intent.putExtra("mimeType", mimeType);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Activity activity = (Activity) this;
activity.startActivity(Intent.createChooser(
intent, activity.getString(R.string.set_as)));
Above answers are great , however here is one i tested and used.
private void setAsWallpaper(String path_of_file) {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_ATTACH_DATA);
File file = new File(path_of_file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setDataAndType(FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file), getMimeType(path_of_file);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "Exception generated", Toast.LENGTH_SHORT).show();
}
}
private static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
and simply call setAsWallpaper(path);
here path is absolute path of file .
I have downloaded the excel file to sdcard. want to open the file in my app and process it.
Is there any way or any intent to open an excel file in android. I
Use the below mentioned code and try:
File file = new File(Environment.getExternalStorageDirectory()+ "/filepath/" + filename);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/vnd.ms-excel");
startActivity(intent);
Use this piece of code which can be used to open arbitrary file (not only Excel).
General idea is to get based on file mime type which Intent can handle it and then start those Intent. For sure it may happen that system doesn't have any intents to handle it or may have several Intents. Anyway here's general direction:
Get mime type for given filename
public String getMimeType(String filename)
{
String extension = FileUtils.getExtension(filename);
// Let's check the official map first. Webkit has a nice extension-to-MIME map.
// Be sure to remove the first character from the extension, which is the "." character.
if (extension.length() > 0)
{
String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
if (webkitMimeType != null)
return webkitMimeType;
}
return "*/*";
}
Then get default intent which will handle given mime type
public Intent getDefaultViewIntent(Uri uri)
{
PackageManager pm = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
// Let's probe the intent exactly in the same way as the VIEW action
String name=(new File(uri.getPath())).getName();
intent.setDataAndType(uri, this.getMimeType(name));
final List<ResolveInfo> lri = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if(lri.size() > 0)
return intent;
return null;
}
And as final step just start Intent returned by getDefaultViewIntent()
Try this:
public void ouvrir(View view) {
String csvFile = "myData.xls";
File yourDir = new File(Environment.getExternalStorageDirectory()+ "/CHETEHOUNA/" + csvFile);
String davUrl = "ms-excel:ofv|u|" + yourDir.toString();
Uri uri = Uri.parse(davUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
Uri path = Uri.fromFile(file);
Intent excelIntent = new Intent(Intent.ACTION_VIEW);
excelIntent.setDataAndType(path , "application/vnd.ms-excel");
excelIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(excelIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(EmptyBlindDocumentShow.this,"No Application available to viewExcel", Toast.LENGTH_SHORT).show();
}
Can you elaborate?
If you want to read excel file from SD card using File, here is the code
File root = Environment.getExternalStorageDirectory();
File excelFile = new File(root, "filename.xlsx");