Android - How do I open a file in another app via Intent? - android

I'm trying to open a file using another app, i.e. opening a .jpg with Gallery, .pdf with Acrobat, etc.
The problem I'm having with this is when I try to open the file in the app, it only opens the chosen app instead of opening the file within the app. I tried following Android open pdf file via Intent but I must be missing something.
public String get_mime_type(String url) {
String ext = MimeTypeMap.getFileExtensionFromUrl(url);
String mime = null;
if (ext != null) {
mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
return mime;
}
public void open_file(String filename) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), filename);
// Get URI and MIME type of file
Uri uri = Uri.fromFile(file).normalizeScheme();
String mime = get_mime_type(uri.toString());
// Open file with user selected app
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
intent.setType(mime);
context.startActivity(Intent.createChooser(intent, "Open file with"));
}
As far as I can tell, it returns the right URI and MIME type:
URI: file:///storage/emulated/0/Download/Katamari-ringtone-985279.mp3
MIME: audio/mpeg

Posting my changes here in case it can help someone else. I ended up changing the download location to an internal folder and adding a content provider.
public void open_file(String filename) {
File path = new File(getFilesDir(), "dl");
File file = new File(path, filename);
// Get URI and MIME type of file
Uri uri = FileProvider.getUriForFile(this, App.PACKAGE_NAME + ".fileprovider", file);
String mime = getContentResolver().getType(uri);
// Open file with user selected app
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, mime);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}

I used this piece of code and it worked perfectly fine on android 6 and below not tested on the higher version
public void openFile(final String fileName){
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(android.os.Environment.getExternalStorageDirectory()
.getAbsolutePath()+ File.separator+"/Folder/"+fileName));
intent.setDataAndType(uri, "audio/mpeg");
startActivity(intent);
}

Related

how to intstall mcpack in minecraft programatically android

i'm trying to send (install) my mcpack file using this code but is is not working, minecraft support this type of extenstion to install mods (.mcpack, .mcaddon, .mcworld, .mctemplate, .modpkg how we can define mimetypes for these extensions)
please go through this image i need exactly like this https://imgur.com/14rIBvN
try {
//File path = new File(getFilesDir(), "dl");
File file = new File(path);
PackageManager manager = this.getPackageManager();
// Get URI and MIME type of file
Intent share = new Intent(Intent.ACTION_SEND);
//share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
share.setPackage("com.mojang.minecraftpe");//package name of the app
startActivity(Intent.createChooser(share, "Select Minecraft to install"));
} catch (Exception e) {
Log.i(TAG, "App not found.. "+e.getMessage());
}
i did it!)
File file = new File(this.getExternalFilesDir(null), "1.mcpack");
Uri photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
// set the content type and data of the intent
intent.setDataAndType(photoURI, "application/octet-stream");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// start the intent as a new activity
startActivity(intent);
Open with minecraft and it will open and it will day download started and if it works it will say, If it does not work it will say, Minecraft onlu supports .mcpack, .mcworld, .mctemplate on pocket edition

share file over bluetooth opp in Android N

What i am trying is to share a file over bluetooth. I have tried below two methods to pass the file name to the ACTION_SEND intend. share activity is pop'ing up and when i touch the connected bluetooth device, i get a toast saying Bluetooth share: File Unknown file not sent. Both the method fails.
public void pushFileOverOpp(String filename) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setPackage("com.android.bluetooth");
intent.setType("audio/mp3");
File f = new File(Environment.getExternalStorageDirectory(), "images");
File sample = new File(f, "sample.mp3");
Uri u = Uri.parse(sample.toString());
intent.putExtra(Intent.EXTRA_STREAM, u);
mContext.startActivity(intent);
}
Error , Log-
OppService: URI : /storage/emulated/0/images/sample.mp3
OppService: HINT : null
OppService: FILENAME: null
OppService: MIMETYPE: audio/mp3
File f = new File(mContext.getFilesDir(), "images");
File sample = new File(f, "sample.mp3");
Uri u = FileProvider.getUriForFile(mContext,
BuildConfig.APPLICATION_ID + ".provider", sample);
intent.putExtra(Intent.EXTRA_STREAM, u);
Error, Log-
OppService: URI : content://com.example.com.test.provider/tester/images/sample.mp3
OppService: HINT : null
OppService: FILENAME: null
I have checked the android source code, This error comes when filename is null. Log also says filename is null. But i could not figure out the exact reason. Could someone Please help me out here, what is wrong with my code.
After some study i understood the problem. There were two issues-
xml tag for external storage(/sdcard/) directory was wrong in xml file.
I changed as below.
<root-path
name="root"
path="/" />
URI permission was not granted
mContext.grantUriPermission("com.android.bluetooth", u,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
After modifying with above lines of code, File share is working !
full working code-
public boolean pushFileOverOpp(String filename) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("*/*"); // supports all mime types
intent.setPackage("com.android.bluetooth"); //bluetooth package name, default opp
File folder = new File(Environment.getExternalStorageDirectory(), "images");
File file = new File(folder, filename);
if (!file.exists()) {
Logger.e("No such file " + filename + " exists!");
return false;
}
Uri u = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".provider", file);
intent.putExtra(Intent.EXTRA_STREAM, u);
mContext.grantUriPermission("com.android.bluetooth", u,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
Logger.d("Sharing file over bluetooth " + folder.toString());
mContext.startActivity(intent);
return true;
}
Thanks.
Please refer this code , it works and share the files using createChooser method.
ArrayList<Uri> arrayList2 = new ArrayList<>();
String MEDIA_PATH = new String(Environment.getExternalStorageDirectory() +
"/NewCallLogs/audio.mp3");
File files = new File(MEDIA_PATH);
Uri u = Uri.fromFile(files);
arrayList2.add(u);
Intent share = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
share.setData(Uri.parse("mailto:"));
share.setType("audio/mpeg");
share.putExtra(android.content.Intent.EXTRA_STREAM, arrayList2);
try {
startActivity(Intent.createChooser(share, "Share..."));
// getActivity().finish();
Log.i("Finished sharing.", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(), "nothing shared.", Toast.LENGTH_SHORT).show();
}
For sharing the file only in bluetooth
ArrayList<Uri> arrayList2 = new ArrayList<>();
String MEDIA_PATH = new String(Environment.getExternalStorageDirectory() +
"/NewCallLogs/audio.mp3" );
File files = new File(MEDIA_PATH);
Uri u = Uri.fromFile(files);
arrayList2.add(u);
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setData(Uri.parse("mailto:"));
share.setType("audio/mpeg");
share.setPackage("com.android.bluetooth");
share.putExtra(android.content.Intent.EXTRA_STREAM, arrayList2);
startActivity(share);

Open any type of file of Android without declaring MIME type explicitly

I am using this method to open launch an Intent to open a file on Android (I've described my problems in the comments):
public static void openFile(Context context, String fileName) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setType(FileHelper.getMimeType(file)); // this doesn't work for PDF files
// opens Intent but then the chosen application doesn't open the file
intent.setType("application/pdf"); // this works correctly for PDF files
intent.setData(Uri.parse("file://" + getPath(context) + fileName));
context.startActivity(intent);
}
I would like to have a single method that would open any kind of file, without having to explicitly specify the MIME type, is that possible?
Mime type is needed to open the file i.e. we have to set Data and Type. You can use this function to open any file:
public void openFile(Context ctx,String filepath)
{
Uri ttt = Uri.parse("file://" + filepath);
Intent intent = new Intent(Intent.ACTION_VIEW);
String arr[] = filepath.split("\\.");
MimeTypeMap myMime = MimeTypeMap.getSingleton();
String mimeType = myMime.getMimeTypeFromExtension(arr[arr.length - 1]);
intent.setDataAndType(ttt, mimeType);
ctx.startActivity(intent);
}
However, there will be problem in files without extension.

How do I open a file externally?

I have files like .doc .pdf .excel... and i want to open them externally.
I tried intent.ACTION_VIEW but it open it in the browser.
How can I open them with which ever application the user has as a default handler?
File file = new File(Globals.SAVE_PATH + filename);
openFile(file.toURI());
public void openFile(URI uri) {
Intent i = new Intent(?????);
i.setData(Uri.parse(uri.toString()));
startActivity(i);
}
You might find this article useful. The thing you must remember is that if the phone has only one app that is capable of opening the file, it will launch automatically.
Thanks for your answers but I found this method to be the easiest.
String path="File Path";
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=file.getName().substring(file.getName().lastIndexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file),type);
startActivity(intent);

How to open an excel file in android

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");

Categories

Resources