how to get list of installed instant messenger apps? - android

My app should be able to send the text in a TextView via WhatsApp, Email, SMS etc. For that i need a list of installed Messging Applications. I tried it with the PackageManger but i get all apps. How can i get only the Instant Messaging Apps?
This is my code to list the installed apps:
PackageManager packageManager=this.getPackageManager();
List<PackageInfo> applist=packageManager.getInstalledPackages(0);
Iterator<PackageInfo> it=applist.iterator();
while(it.hasNext()){
PackageInfo pk=(PackageInfo)it.next();
if(PackageManager.PERMISSION_GRANTED==(packageManager.checkPermission(Manifest.permission.INTERNET, pk.packageName)& packageManager.checkPermission(Manifest.permission.RECEIVE_SMS, pk.packageName))) //checking if the package is having INTERNET permission
{
myList.add(""+pk.applicationInfo.loadLabel(packageManager));
}
}

Supposed you manage to get the list of the apps you want, then what are you going to do with them?
I think that you need to let android to present a list of apps to your users for them to choose which application they want to handle the text, depending on the action performed. Fortunately this is a build in feature in Android. Here is my function for sending e-mails:
public static void StartEmailIntent (Context cx, String EmailAddress){
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
email.putExtra(Intent.EXTRA_EMAIL, new String[]{EmailAddress});
cx.startActivity(Intent.createChooser(email, cx.getString(R.string.dlg_sendmail_selectortitle)));
}
As you can see I am setting Intent.ACTION_SEND as the action and then with the Intent.createChooser android creates a list of applications capable to handle that action based on the type and the extras of the Intent. It shouldn't be hard to adapt other actions like SMS, Phone calls etc. You can read more about it here Sending Content to Other Apps
Hope this helps...

If you are targeting Ice Cream Sandwich you should go with the ShareActionProvider. There you get your desired list of ways to share whatever you want.
You could also read this android-developer-blogpost where they explain how to share via intent. So for example for your emailsharing:
Intent intent=new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Add data to the intent, the receiving app will decide what to do with it.
intent.putExtra(Intent.EXTRA_SUBJECT, “Some Subject Line”);
intent.putExtra(Intent.EXTRA_TEXT, “Body of the message, woot!”);

Related

Suggest several apps in playstore to user (Similar to Share dialog)

My app forwards users to a different app to perform a specific action (e.g. ACTION_SHARE, except that the apps that I forward users to do not implement an intent filter) Since they don't implement intent filters, I have a list of package names that support the action.
This part is working fine, like this:
for (String knownApp : knownApps) {
Intent intent = pm.getLaunchIntentForPackage(knownApp);
if (intent != null) {
ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
intentList.add(new LabeledIntent(intent, knownApp, resolveInfo.loadLabel(pm), resolveInfo.icon));
}
}
LabeledIntent[] extraIntents = intentList.toArray(new LabeledIntent[intentList.size()]);
Intent openInChooser = Intent.createChooser(actionIntent, getString(R.string.perform_action_with));
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
startActivity(openInChooser);
If the user has none of the apps installed, I want to give the user a choice of apps to download to fulfill the action.
Currently that looks like this.
As you can see it's lacking both icon and name. For regular apps I use an intent chooser which needs LabledIntent, but on one hand, I can't get the name and icon from the playstore unless I scrape them (which is not allowed by google, besides LabledIntent requires a resourceId as the Icon, which I can't get for downloaded files.), on the other the intent chooser won't seem to display the intent unless the package name of the intent and LabeledIntent match. This does not work for URIs which I'm using to access the Play Store in the first place.
Now I'm looking for ideas on how to get the following code to display both the correct name and app icon, as well as forward to the correct page on the play store.
protected void showPlayStoreOptions(List<String> knownApps) {
Intent chooserIntent = new Intent();
Intent showIntent = Intent.createChooser(chooserIntent, "You need one of these Apps on Google Play..."); //googles brand guidelines state that "on Google Play" has to be used
List<Intent> list = new ArrayList<>();
for (String knownApp : knownApps) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + knownApp)); //normally you would try an uri with market:// first, catch the exception if no playstore is installed and then use this, but the intent chooser seems to automatically forward correctly.
list.add(intent);
//list.add(new LabeledIntent(intent, "https://play.google.com/store/apps/details?id=" + knownApp, "test name", R.drawable.icon_info));
//list.add(new LabeledIntent(intent, ""+Uri.parse("https://play.google.com/store/apps/details?id=" + knownApp), "test name", R.drawable.icon_info));
}
showIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, list.toArray(new Intent[list.size()]));
startActivity(showIntent);
}
So to sum up my questions.
How can I get a resource Id from a downloaded image file, or how can I use the downloaded image file with a LabledIntent.
(Extending LabledIntent does not work due to issues with parceling (and those methods are package private))
How can I display a LabledIntent in a choose intent with an URI?
I realize it's probably easier to write my own chooser, but I want to wrangle this into the default android system.

Android intent not showing only email clients

So I'm trying to launch a prepopulated email client with data. The content gets populated fine, however my problem is that when launching the intent, I wanted it to only show email clients to select from.
Instead, it shows Gmail, Adding to EverNote, Android Beam, Bluetooth, and some others.
I don't know if its an issue with lollipop that broke this functionality or not, as one of my managers sent me code that worked fine for him a few years ago.
My code is:
private void openEmailClient(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{getResources().getString(R.string.contact_feedback_email_address)});
intent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.contact_feedback_email_subject_android));
try{
startActivity(Intent.createChooser(intent,intentEmailString));
} catch(android.content.ActivityNotFoundException ex){
Log.e(EMAIL_FAIL_TAG, EMAIL_FAIL);
ex.printStackTrace();
}
}
when you will change your intent.setType like below you will get
intent.setType("text/plain");
Use
android.content.Intent.ACTION_SENDTO
(new Intent(Intent.ACTION_SENDTO);) to get only the list of e-mail clients, with no facebook or other apps. Just the email clients.
I wouldn't suggest you get directly to the email app. Let the user choose his favorite email app. Don't constrain him.
If you use ACTION_SENDTO, putExtra does not work to add subject and text to the intent. Use Uri to add the subject and body text.
We can use message/rfc822 instead of "text/plain" as the MIME type. However, that is not indicating "only offer email clients" -- it indicates "offer anything that supports message/rfc822 data". That could readily include some application that are not email clients.
message/rfc822 supports MIME Types of .mhtml, .mht, .mime
EDIT
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:someone#example.com"));
intent.putExtra("subject", "my subject");
intent.putExtra("body", "my message");
startActivity(intent);
its working ...
So I solved it. Not ideally but it works better than anything else I have tried.
I followed the google docs on doing it, which says to do this:
public void composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
and it now works.
This just finds a default app for handling mail. I'm not sure how it decides, but in my case it opened GMail. On a device without GMail installed, such as the Galaxy S5, it opened their mail client and prompted the user to set up email.
Doesn't give choice of app but it works
Try like this it working fine for me...
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:abc#gmail.com"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Test App");
intent.putExtra(Intent.EXTRA_TEXT, "Email Body");
startActivity(intent);
Note: it only work if you have email address.
For more information please refer this link Android - Is there a foolproof way to only show possible EMAIL clients?

Opening an email with multiple attachments, while restricting the chooser to ONLY email apps?

What is the best way on Android to send an email with multiple attachments without having non-email apps in the chooser?
When sending emails, I used to do it like this:
final Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.setType("message/rfc822");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "test#test.com" });
...
Unfortunately, "message/rfc822" no longer works well for filtering out undesired apps from the chooser, such as Evernote, Drive, and various other apps.
I recently found this workaround that works for single attachments:
sendEmailIntent = new Intent(Intent.ACTION_SENDTO);
Uri data = Uri.parse("mailto:?to=test#test.com&subject...");
sendEmailIntent.setData(data);
...
Unfortunately, this doesn't work for multiple attachments. I tried it, and it crashes Gmail. :S
I finally found a solution, albeit one that only works on Ice Cream Sandwich MR1 and above. The trick is to first build your intent using ACTION_SEND_MULTIPLE:
sendEmailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
sendEmailIntent.setType("message/rfc822");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "some#email.com" });
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
final ArrayList<Uri> uris = /* ... Your code to build the attachments. */
sendEmailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
To restrict it to email apps only, add this code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
sendEmailIntent.setType(null); // If we're using a selector, then clear the type to null. I don't know why this is needed, but it doesn't work without it.
final Intent restrictIntent = new Intent(Intent.ACTION_SENDTO);
Uri data = Uri.parse("mailto:?to=some#email.com");
restrictIntent.setData(data);
sendEmailIntent.setSelector(restrictIntent);
}
When you fire this intent with startActivity(), you'll now only see email apps in the list, and if you select Gmail, the multiple attachments will be there.
I do this with a try/catch in case startActivity resolves to no activities, in which case I remove the selector, and it seems to work well.

Sharing Content On FaceBook Android

I use intent and Action.SEND for sharing my custom message on social networks like WhatsApp , twitter, Facebook and GMail. Everything is ok on Gmail and other applications except Facebook! How can I customize my code to share something on Facebook as well? I do share on Facebook using Facebook SDK with no problem, but I want to do it using an intent.
this is what I use:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, knowTitle+"Read the full article via MomsApp by EnfaMama A+ at http://meadjohnsonasia.com.my/mobileapp");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "I just read "+knowTitle);
sendIntent.setType("*/*");
startActivity(Intent.createChooser(sendIntent, "Share Your Favorite Article"));
What I did was actually to intercept the chosen target of the intenthandlers, you can do that by using your actionprovider. Let's say you created an item that with an onclick starts the intent. In order to do that, you can instantiate an actionprovider to do so. This actionprovider can have a setOnShareTargetSelectedListener to intercept any intents that you want to handle differently (or not at all ^^). See the code below for how to configure your actionprovider.
actionProvider.setShareIntent(createShareIntent());
actionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener(){
#Override
public boolean onShareTargetSelected(ShareActionProvider source,
Intent intent) {
if ("com.facebook.katana".equals(intent.getComponent().getPackageName()) && mfacebooksharer != null) {
mfacebooksharer.shareStatus(subject, text);
return true;
}
return false;
}
});
Whenever facebook is chosen, I use my mfacebooksharer to handle the intent and follow the facebook API.
Ofcourse, that actionrpovider needs to have an intent. (Just like you wanted to work with an intent). I use the method below to create the intent.
private Intent createShareIntent() {
intentsetter.setIntentleave(true);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, text);
return shareIntent;
}
As per the Facebook's Platform Policies, you cannot pre-fill the share dialog using
Intent.EXTRA_TEXT. It is usually thought to be a bug, but as per a Bug Report filed here and also, here, Facebook clearly mentions that this is not the case (it's not a bug).
You can read more about their Platform Policies specifically, Platform Policy IV.2
Quote from Platform Policy IV.2:
You must not pre-fill any of the fields associated with the following
products, unless the user manually generated the content earlier in
the workflow: Stream stories (user_message parameter for
Facebook.streamPublish and FB.Connect.streamPublish, and message
parameter for stream.publish), Photos (caption), Videos (description),
Notes (title and content), Links (comment), and Jabber/XMPP.
These fields are intended for users to express themselves. Pre-filling
these fields erodes the authenticity of the user voice.
The only way you can share stories from your App is by integrating the Facebook SDK, which as per your post, you are already able to successfully. That is the only option available (unfortunately).
Using Intent in Android, you can share only a link without text:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "http://www.google.ca");
startActivity(Intent.createChooser(intent, "Share with"));
It'll work. If you want to share text and link , you have to use the Facebook SDK for Android: https://github.com/facebook/facebook-android-sdk

Android Intent for Twitter application

Is it possible to show a list of applications (with intent.createChooser) that only show me my twitter apps on my phone (so htc peep (htc hero) or twitdroid). I have tried it with intent.settype("application/twitter") but it doesnt find any apps for twitter and only shows my mail apps.
Thank you,
Wouter
I'm posting this because I haven't seen a solution yet that does exactly what I want.
This primarily launches the official Twitter app, or if that is not installed, either brings up a "Complete action using..." dialog (like this) or directly launches a web browser.
For list of different parameters in the twitter.com URL, see the Tweet Button docs.
Remember to URL encode the parameter values. (This code is specifically for tweeting a URL; if you don't want that, just leave out the url param.)
// Create intent using ACTION_VIEW and a normal Twitter url:
String tweetUrl = String.format("https://twitter.com/intent/tweet?text=%s&url=%s",
urlEncode("Tweet text"),
urlEncode("https://www.google.fi/"));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(tweetUrl));
// Narrow down to official Twitter app, if available:
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
if (info.activityInfo.packageName.toLowerCase().startsWith("com.twitter")) {
intent.setPackage(info.activityInfo.packageName);
}
}
startActivity(intent);
(URL encoding is cleaner if you have a little utility like this somewhere, e.g. "StringUtils".)
public static String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
}
catch (UnsupportedEncodingException e) {
Log.wtf(TAG, "UTF-8 should always be supported", e);
throw new RuntimeException("URLEncoder.encode() failed for " + s);
}
}
For example, on my Nexus 7 device, this directly opens the official Twitter app:
If official Twitter app is not installed and user either selects Chrome or it opens automatically (as the only app which can handle the intent):
The solutions posted before, allow you to post directly on your first twitter app. To show a list of twitters app (if there are more then one), you can custom your Intent.createChooser to show only the Itents you want.
The trick is add EXTRA_INITIAL_INTENTS to the default list, generated from the createChoose, and remove the others Intents from the list.
Look at this sample where I create a chooser that shows only my e-mails apps. In my case appears three mails: Gmail, YahooMail and the default Mail.
private void share(String nameApp, String imagePath) {
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/jpeg");
List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
if (!resInfo.isEmpty()){
for (ResolveInfo info : resInfo) {
Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
targetedShare.setType("image/jpeg"); // put here your mime type
if (info.activityInfo.packageName.toLowerCase().contains(nameApp) ||
info.activityInfo.name.toLowerCase().contains(nameApp)) {
targetedShare.putExtra(Intent.EXTRA_TEXT, "My body of post/email");
targetedShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imagePath)) );
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
}
}
Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select app to share");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
startActivity(chooserIntent);
}
}
You can run like that: share("twi", "/sdcard/dcim/Camera/photo.jpg");
This was based on post: Custom filtering of intent chooser based on installed Android package name
This question is a bit older, but since I have just come across a similar problem, it may also still be of interest to others. First, as mentioned by Peter, create your intent:
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.putExtra(Intent.EXTRA_TEXT, "Test; please ignore");
tweetIntent.setType("application/twitter");
"application/twitter" is in fact a known content type, see here. Now, when you try to start an activity with this intent, it will show all sorts of apps that are not really Twitter clients, but want a piece of the action. As already mentioned in a couple of the "why do you even want to do that?" sort of answers, some users may find that useful. On the other hand, if I have a button in my app that says "Tweet this!", the user would very much expect this to bring up a Twitter client.
Which means that instead of just launching an activity, we need to filter out the ones that are appropriate:
PackageManager pm = getPackageManager();
List<ResolveInfo> lract
= pm.queryIntentActivities(tweetIntent,
PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for(ResolveInfo ri: lract)
{
if(ri.activityInfo.name.endsWith(".SendTweet"))
{
tweetIntent.setClassName(ri.activityInfo.packageName,
ri.activityInfo.name);
resolved = true;
break;
}
}
You would need to experiment a bit with the different providers, but if the name ends in ".SendTweet" you are pretty safe (this is the activity name in Twidroyd). You can also check your debugger for package names you want to use and adjust the string comparison accordingly (i.e. Twidroyd uses "com.twidroid.*").
In this simple example we just pick the first matching activity that we find. This brings up the Twitter client directly, without the user having to make any choices. If there are no proper Twitter clients, we revert to the standard activity chooser:
startActivity(resolved ? tweetIntent :
Intent.createChooser(tweetIntent, "Choose one"));
You could expand the code and take into account the case that there is more than one Twitter client, when you may want to create your own chooser dialog from all the activity names you find.
It is entirely possible your users will only ever, now and forever, only want to post to Twitter.
I would think that it is more likely that your users want to send information to people, and Twitter is one possibility. But, they might also want to send a text message, or an email, etc.
In that case, use ACTION_SEND, as described here. Twidroid, notably, supports ACTION_SEND, so it will appear in the list of available delivery mechanisms.
These answers are all overly complex.
If you just do a normal url Intent that does to Twitter.com, you'll get this screen:
which gives you the option of going to the website if you have no Twitter apps installed.
String url = "https://twitter.com/intent/tweet?source=webclient&text=TWEET+THIS!";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Either
You start an activity with an Intent with action Intent.ACTION_SEND and the text/plain MIME type. You'll have all applications that support sending text. That should be any twitter client, as well as Gmail, dropbox, etc.
Or, you try to look up for the specific action of every client you are aware of, like "com.twitter.android.PostActivity" for the official client. That will point to this client, and that is unlikely to be a complete list.
Or, you start with the second point, and fall back on the first...
Nope. The intent type is something like image/png or application/pdf, i.e. a file type, and with createChooser you're basically asking which apps can open this file type.
Now, there's no such thing as an application/twitter file that can be opened, so that won't work. I'm not aware of any other way you can achieve what you want either.
From http://twidroid.com/plugins/
Twidroid’s ACTION_SEND intent
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is a sample message via Public Intent");
sendIntent.setType("application/twitter");
startActivity(Intent.createChooser(sendIntent, null));
I used "billynomates" answer and was able to use hashtags by using the "URLEncoder.encode(, "UTF-8")" function. The hash tags showed up just fine.
String originalMessage = "some message #MESSAGE";
String originalMessageEscaped = null;
try {
originalMessageEscaped = String.format(
"https://twitter.com/intent/tweet?source=webclient&text=%s",
URLEncoder.encode(originalMessage, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(originalMessageEscaped != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(originalMessageEscaped));
startActivity(i);
}
else {
// Some Error
}

Categories

Resources