Send File Path in order to choose the respective application to open in Android - android

In my application I will have list with different file paths.
Example list:
/storage/emulated/0/Edited/myjpeg_file.JPG
/storage/emulated/0/Downloads/bill.pdf
/storage/emulated/0/Downloads/mytextfile.txt
This list is showed in list view. When I click on one entry, it should open list of supported installed applications to process it further.
When I click on entry wit .JPG then it should show apps related to that.
And If i select .pdf file it should show supported apps
And for all paths default it should show file browser such as default file manager , Es Explorer etc...
I am referring to
http://developer.android.com/training/sharing/send.html
But need the selection based on file type (txt, xml, pdf jpeg etc..).
If i select .JPG file it is not showing gallery or Es file explorer (i have it on my mobile)
In same way when I click on .pdf file it is not showing adobe reader etc..
Below is my code:
public void openFile(String minmeType, Uri uriFromPath) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriFromPath);
if(minmeType.contains("text/plain")) {
shareIntent.setType("text/plain");
} else {
shareIntent.setType("image/jpeg");
}
startActivity(Intent.createChooser(shareIntent, "sending out"));
}
Above function is called from below code:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String path = pathList[position];
Uri uriFromPath = Uri.fromFile(new File(path));
Toast.makeText(getActivity().getApplicationContext(),"Uri: "+ uriFromPath, Toast.LENGTH_LONG).show();
if(path.contains(".JPG")) {
openFile("image/*", uriFromPath);
} else {
openFile("text/plain", uriFromPath);
}
return;
}
});

Have you tried using ACTION_VIEW instead of ACTION_SEND?
ACTION_SEND implies you want to send the document to somebody else. Adobe Reader won't catch those Intents that want to do ACTION_SEND, because sending pdfs is not what they do. VIEWing them, on the other hand, is.
You also need to match the intent that the target application is filtering for.
In this case, it's pretty simple what you want to do: you want Adobe Reader to open your file. And Adobe Reader actually has the intent filter you would expect. If you look into its Manifest file, you'll see that (among others) it includes an intent filter that matches Uris with schema file, any host, and any path that ends in .pdf. If you change your openFile method to this:
public void openFile(Uri uriFromPath) {
Intent shareIntent = new Intent(Intent.ACTION_VIEW, uriFromPath);
startActivity(Intent.createChooser(shareIntent, "sending out"));
}
It will work. It should also work for most apps that handle content from files.

Related

Android: Image resolution difference when sharing through Intent.EXTRA_STREAM

I have a menu option to share my app which generates an ArrayList of Uris object with a list of drawables Uris, and my issue is I've saved all the screenshots in 540x1170px and they get to email in 1620x3510px (curiously? exactly the triple), and in the mail they look too big.
This next is the code I use to share the images, and I'd like to know the reason why the original resolution is altered, and if there is a way to set intent image resolution.
public static void shareFile(ArrayList<Uri> uris, String fileType)
{
try{
Intent share = new Intent(Intent.ACTION_SEND_MULTIPLE);
share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.setType(fileType);
String strSubject = TMLocale.getStringResourceByName("mainmenu_sharethisapp_subject");
share.putExtra(Intent.EXTRA_SUBJECT, strSubject);
share.putExtra(Intent.EXTRA_TEXT, TMLocale.getStringResourceByName("mainmenu_sharethisapp_recommendtext"));
share.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
activity.get().startActivity(Intent.createChooser(share, TMLocale.getStringResourceByName("mainmenu_sharethisapp_shareapptitle")));
}
catch(Exception ex){
Toast.makeText(activity.get(), String.valueOf(ex.getMessage()),Toast.LENGTH_LONG).show();
}
}
And I call it setting "image/jpg" as fileType.

How to share text in Instagram

I need share text to instagram but I can't use android
intent.putExtra(Intent.EXTRA_TEXT,"MY TEXT");
nothing happen.please help me to do this
Instagram have stopped accepting pre-populated capitions to increase the quality of content in the system. See this post.
http://developers.instagram.com/post/125972775561/removing-pre-filled-captions-from-mobile-sharing
Generic code for sharing text with any social app :
Step1 : Get the package name of app you wanna share :
To get the package name use adb logcat -s ActivityManager this command in windows and run the app like for example you want package name for instagram so run above command and open instagram app you would get the package name in logs
Note : the adb command listed above is for windows .
For ubntu you can use adb logcat | grep "ActivityManager"
STEP 2 : Once you got the package name of app below is generic code for sharing text .
try {
Intent shareOnAppIntent = new Intent();
shareOnAppIntent .setAction(Intent.ACTION_SEND);
shareOnAppIntent .putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_body));
shareOnAppIntent .setType("text/plain");
shareOnAppIntent .setPackage(PACKAGE_NAME_OF_APP);
startActivity(shareOnAppIntent );
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(ShareAppActivity.this, "APP is not installed", Toast.LENGTH_LONG).show();
}
Unfortunately Instagram doesn't receives text from intent. it receives only EXTRA_STREAM object. you can share only images of format jpeg, gif, png. Since they are not providing any SDK you cant share in any other way.
Check Instagram developer documentation here they were clearly mentioning that the accepting Intent Parameter as EXTRA_STREAM
This is the code for sharing photo in Instagram
String type = "image/*";
String filename = "/myPhoto.jpg";
String mediaPath = Environment.getExternalStorageDirectory() + filename;
createInstagramIntent(type, mediaPath);
private void createInstagramIntent(String type, String mediaPath){
// Create the new Intent using the 'Send' action.
Intent share = new Intent(Intent.ACTION_SEND);
// Set the MIME type
share.setType(type);
// Create the URI from the media
File media = new File(mediaPath);
Uri uri = Uri.fromFile(media);
// Add the URI to the Intent.
share.putExtra(Intent.EXTRA_STREAM, uri);
// Broadcast the Intent.
startActivity(Intent.createChooser(share, "Share to"));
}
Here is the intent code to share image and text in Instagram.
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM,uri);
shareIntent.putExtra(Intent.EXTRA_TEXT,"YOUR TEXT TO SHARE IN INSTAGRAM");
shareIntent.setPackage("com.instagram.android");
return shareIntent;

How can i send either an image or a video file using ACTION_SEND?

I want to share either an image or a video file using ACTION_SEND. So basically when the users taps on an image and selects "share image/video" it should send either the image selected or the video selected.
here is my code i am using:
if (filep != null) {
}
File sending=new File(filep);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_SEND);
intent.setDataAndType(Uri.fromFile(sending),getMimeType(sending.getAbsolutePath()));
intent.putExtra(Intent.EXTRA_STREAM, sending);
startActivity(Intent.createChooser(intent , "Share"));
}
private String getMimeType(String url)
{
String parts[]=url.split("\\.");
String extension=parts[parts.length-1];
String type = null;
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
return type;
So when testing, it takes me to which app i want to use to share with i.e whatsapp, Facebook, email etc. And then when selecting either one, it then says "sharing failed, please try again." I can't seem to figure out why it doesn't work. However i have the same code to display either image or video file full screen with ACTION_VIEW and that seems to work great but not with sharing.
Can anyone assist please?
EXTRA_STREAM needs to be a Uri, and you are not passing a Uri. Use Uri.fromFile() to construct a Uri.
Also, replace setDataAndType() with setType(), as ACTION_SEND does not use the data aspect of the Intent.

Browse path on SD card via Intent

I'd like to know if there's a way to open a file browser (system or 3rd party like Astro) to a specific path. There's not much else to say here... pretty straight-forward question.
Sounds like ACTION_GET_CONTENT is what you want. See here. The relevant bits would be:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
On my phone (which has astro already installed), this brings up an astro dialog for /sdcard. I'm not sure what this will do on a phone with no file browser installed. I'm also unsure about whether you are able to actually specify the starting path using this method. The docs make it sound like you can't specify a starting uri for ACTION_GET_CONTENT.
EDIT: I think I understand the question better now. I thought you were wanting a picker style browser to just get a file path from the user. If you want a full blown browser to handle your uri, then this worked for me:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file:///mnt/sdcard/Music"), "*/*");
startActivity(intent);
That will probably give you quite a long list of possible handlers, but I'd bet any file manager on the system would be in the list (astro certainly is).
I don't believe that any of the manufacturer provided File Browsers provide such a thing.
Though I don't see anything glaringly wrong with the theory of doing so. I imagine you are more likely to find a 3rd party file browser with this feature, but I've never come across any of those either.
You might look in to the Open Intents OI File Manager this concept seems right up their ally, if they don't already have this feature, I bet they might consider adding it if you get in contact with them.
Here i am going to show you that how to create a BROWSE button, which when you will click, it will open up the SDCARD, you will select a File and in result you will get the File Name and File path of the selected one:
// A button which you will hit**
browse.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
startActivityForResult(intent, PICK_REQUEST_CODE);
}
});
//The function which will get the Resulted File Name and File Path
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
Uri uri = intent.getData();
if (uri.getScheme().toString().compareTo("content")==0)
{
Cursor cursor =getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
Uri filePathUri = Uri.parse(cursor.getString(column_index));
String file_name = filePathUri.getLastPathSegment().toString();
String file_path=filePathUri.getPath();
Toast.makeText(this,"File Name & PATH are:"+file_name+"\n"+file_path, Toast.LENGTH_LONG).show();
}
}
}
}
}

How do I determine if Android can handle PDF

I know Android cannot handle PDFs natively. However, the Nexus One (and possibly other phones) come pre-installed with QuickOffice Viewer. How would I determine whether the user has a PDF viewer installed?
Currently, the code to start the PDF download looks pretty simple:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
After the download, the user clicks on the downloaded file to invoke the viewer.
However, if there is no PDF viewer, Android reports "Cannot download. The content is not supported on the phone."
I want to determine if the user will get this message, and if so, direct them to PDF apps in the Android Market.
I have been testing this and found that the following works. First you download the file independently and store it on the device and then you go do this:
File file = new File("/sdcard/download/somepdf.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0 && file.isFile()) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
I have tested this on various emulator and a rooted cyanogen phone as well as a HTC Magic. If no pdf renderer is available the list will return zero and nothing will happen.
It seems to be important to set the data type to the pdf mime type to get the correct behaviour.
If you e.g. install droidreader it will react to the intent and display the pdf.
Of course you could do the check before you download the pdf as well depending on your use case or do things like popping up alerts or redirecting do other intents for download or whatever.
Edit: I have since refactored this out into a separate method ..
public static final String MIME_TYPE_PDF = "application/pdf";
/**
* Check if the supplied context can render PDF files via some installed application that reacts to a intent
* with the pdf mime type and viewing action.
*
* #param context
* #return
*/
public static boolean canDisplayPdf(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType(MIME_TYPE_PDF);
if (packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0) {
return true;
} else {
return false;
}
}
You can query the PackageManager to see if there's a package that can handle your Intent. Here's an example: http://www.curious-creature.org/2008/12/15/android-can-i-use-this-intent/
You will probably use asynch task to download any file.so simple way is Just add below code in post execute() method of asynch task.it will ask for choice.
FileOpener.open(context, file);
and file should contain info about filepath and filename.Example
File file = new File(Environment
.getExternalStoragePublicDirectory("/MDroid")
+ filepath + fileName );
Hope it helps

Categories

Resources