check if user is signed into twitter - android

In my app, the user is allowed to tweet something by pressing a button. I am using the following code:
boolean found = false;
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Blah blah");
final PackageManager pm = getPackageManager();
final List<?> activityList = pm.queryIntentActivities(intent, 0);
int len = activityList.size();
for (int i = 0; i < len; i++) {
final ResolveInfo app = (ResolveInfo) activityList.get(i);
if ("com.twitter.android.PostActivity".equals(app.activityInfo.name)) {
found = true;
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.twitter.android", "com.twitter.android.PostActivity");
startActivity(intent);
break;
}
}
if(!found)
showDialog(NO_APP);
The code works perfectly but I want to add a feature to it. When the user is not logged into twitter, I want to display a message saying that he is not logged in. The code, as of right now, just directs the user to the sign in page of twitter. How can I disable this and get the desired output? Thanks!!

For that you can check first that you have the twitterToken and twitterTokenSecret .
Try this way.may it helps :)
if(twitterToken!=null && twitterTokenSecret!=null
&& twitterToken.length()>0 && twitterTokenSecret.length()>0){
//do your work
}else{
//show alert dialog
}

Related

Share via Twitter Native App

I have android app where i am trying to add share feature via twitter.i have successfully implemented where the user can share via Twitter app :
This is my code:
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.setType("text/plain");
tweetIntent.putExtra(Intent.EXTRA_SUBJECT, "tweet");
tweetIntent.putExtra(Intent.EXTRA_TEXT, "sample tweet");
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> lract = pm.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for (ResolveInfo ri : lract) {
if (ri.activityInfo.name.contains("twitter")) {
tweetIntent.setClassName(ri.activityInfo.packageName,
ri.activityInfo.name);
resolved = true;
break;
}
}
if(resolved){
activity.startActivity(tweetIntent);
}else{
// do something
}
Scenarios on click of button:
1) opens the twitter native app and if the user has already logged in it pass the control to post tweet page where my text will be added and on click of post it will successfully post.
ISSUE scenario
If the user has not logged in, user will sign in, after that it will move to Home tab where all the tweets are displayed, instead it should have moved to post tweet page where my text will be added.
how can i fix this issue ?
As I remember this should work with native twitter
String twitterPackage = "com.twitter.android";
String errorMessage = "You should install Twitter app first";
if(isPackageInstalled(twitterPackage, getActivity())){
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.setType("text/*");
tweetIntent.setPackage(twitterPackage);
tweetIntent.putExtra(Intent.EXTRA_TEXT, "sample tweet");
getActivity().startActivity(tweetIntent);
} else {
Toast.makeText(getActivity(), errorMessage, Toast.LENGHT_SHORT).show();// handle error
}

Twitter Login failed

I have downloaded this twitter example. I have replaced the old twitter4j with twitter4j-core-3.0.3.jar and in the onCreate method I put loginToTwitter() in an AsyncTask to avoid getting an NetworkOnMainThreadException. I also created a new app on the twitter dev website and added my consumer key and consumer secret. When I try to Log in, I get the message "Login failed". I downloaded the example because I wanted to see how to accomplish updating your twitter status. How can I fix this problem? Any suggestions will be appreciated.
I used the following code:
Intent shareIntent = findTwitterClient();
shareIntent.putExtra(Intent.EXTRA_TEXT, "added an item to iCollect(Android)! " + strMake + " " + strModel);
startActivity(Intent.createChooser(shareIntent, "Share"));
}catch(NullPointerException e){
Toast.makeText(context, "Twitter app not found", Toast.LENGTH_SHORT).show();
}
public Intent findTwitterClient() {
final String[] twitterApps = {
// package // name - nb installs (thousands)
"com.twitter.android", // official - 10 000
"com.twidroid", // twidroid - 5 000
"com.handmark.tweetcaster", // Tweecaster - 5 000
"com.thedeck.android" }; // TweetDeck - 5 000 };
Intent tweetIntent = new Intent();
tweetIntent.setType("text/plain");
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(
tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (int i = 0; i < twitterApps.length; i++) {
for (ResolveInfo resolveInfo : list) {
String p = resolveInfo.activityInfo.packageName;
if (p != null && p.startsWith(twitterApps[i])) {
tweetIntent.setPackage(p);
return tweetIntent;
}
}
}
return null;
}
The problem with this is if my twitter package list is not up to date, the code may exclude some twitter apps.

Android: Check to see if Facebook app is present on user's device

I've kept a button which takes user to my facebook page.
In order that the official facebook app is opened I use the following url:
fb://pages/PAGE_ID
instead of http://facebook.com/PAGE_ID
Because in that case you get a list of browsers to open the url instead of teh facebook app.
It works if the user has facebook app installed. However it crashes if the user doesn't have facebook app.
Is there any way to check if the user has the facebook app?
Have you already checked this?
You can always check if an app is installed like this.
In an native android app, this is quite easy to achieve:
Uri dataUri = Uri.parse("fb://....");
Intent receiverIntent = new Intent(Intent.ACTION_VIEW, dataUri);
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(receiverIntent, 0);
if (activities.size() > 0) {
startActivity(receiverIntent);
} else {
Uri webpage = Uri.parse("http://www.facebook.com/...");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
packageManager = getPackageManager();
activities = packageManager.queryIntentActivities(webIntent, 0);
if (activities.size() > 0) {
startActivity(webIntent);
}
}
I think you can reuse this code I wrote for checking if twitter app was installed on the device, to check if facebook app is installed. For twitterApps list you have to replace the values by "com.facebook.katana".
public Intent findTwitterClient() {
final String[] twitterApps = { "com.twitter.android", "com.handmark.tweetcaster", "com.seesmic", "com.thedeck.android", "com.levelup.touiteur", "com.thedeck.android.app" };
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.putExtra(Intent.EXTRA_TEXT, "#hashtagTest");
tweetIntent.setType("text/plain");
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (int i = 0; i < twitterApps.length; i++) {
for (ResolveInfo resolveInfo : list) {
String p = resolveInfo.activityInfo.packageName;
if (p != null && p.startsWith(twitterApps[i])) {
tweetIntent.setPackage(p);
return tweetIntent;
}
}
}
return null;
}

Get Preferred/Default app on Android

I am trying to get the default/preferred application for a given Intent. For example, when the user installs a second web browser, then attempts to open a URL, he or she will get a dialog like this:
If the user then selects the Use by default for this action option, then the dialog box no longer opens when a URL is pressed.
I am working on an application that should be aware of what this default or preferred app/action is. How do I do this? I am currently using the code below, but getPreferredPackage doesn't return anything:
Intent i = (new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
PackageManager pm = context.getPackageManager();
final List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
IntentFilter ifilter = new IntentFilter(i.getAction());
if (i.getCategories() != null) {
for(String category : i.getCategories()) {
ifilter.addCategory(category);
}
}
List<IntentFilter> filters = new ArrayList<IntentFilter>();
filters.add(ifilter);
List<ComponentName> preferredActivities = new ArrayList<ComponentName>();
pm.getPreferredActivities(filters, preferredActivities, null);
for (ComponentName activity : preferredActivities) {
for (ResolveInfo rinfo : list) {
if (rinfo.activityInfo.applicationInfo.packageName.equals(activity.getPackageName())) {
try {
final PackageInfo pi = pm.getPackageInfo(activity.getPackageName(), 0);
Toast.makeText(context, pm.getApplicationLabel(pi.applicationInfo), Toast.LENGTH_SHORT).show();
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
What am I doing wrong? Is this even the right approach?
Well, the solution turned out to be much simpler than I made it (although this is very poorly documented). The following code is my solution:
Intent i = (new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
PackageManager pm = context.getPackageManager();
final ResolveInfo mInfo = pm.resolveActivity(i, 0);
Toast.makeText(context, pm.getApplicationLabel(mInfo.activityInfo.applicationInfo), Toast.LENGTH_LONG).show();
The method launchUrlInDefaultBrowser below launches a URL without displaying any selection query for the user. First, it tries to find the user's default browser app and launch the URL with it. Second, if there was no default app, it lists all the capable activities for launching the URL and picks up the first one. In case an activity was launched, the method returns true; otherwise, false.
boolean launchUrlInDefaultBrowser(Context context, String url) {
final Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
browserIntent.setData(Uri.parse(url));
// 1: Try to find the default browser and launch the URL with it
final ResolveInfo defaultResolution = context.getPackageManager().resolveActivity(browserIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (defaultResolution != null) {
final ActivityInfo activity = defaultResolution.activityInfo;
if (!activity.name.equals("com.android.internal.app.ResolverActivity")) {
browserIntent.setClassName(activity.applicationInfo.packageName, activity.name);
context.startActivity(launchIntent);
return true;
}
}
// 2: Try to find anything that we can launch the URL with. Pick up the first one that can.
final List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(browserIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (!resolveInfoList.isEmpty()) {
browserIntent.setClassName(resolveInfoList.get(0).activityInfo.packageName, resolveInfoList.get(0).activityInfo.name);
context.startActivity(browserIntent);
return true;
}
return false;
}
Beware, the OEMs may have their own ResolverActivity implementation. E.g. Huawei has com.huawei.android.internal.app.HwResolverActivity.
In Kitkat AOSP, getPreferredPackages() always returns empty list. Source code as below
public List<PackageInfo> getPreferredPackages(int flags) {
return new ArrayList<PackageInfo>();
}

Android email chooser

I am writing an app that needs to send emails at the end of each transaction. I am doing the following:
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("text/html");
mail.putExtra(Intent.EXTRA_EMAIL, new String[] { emailTo });
mail.putExtra(Intent.EXTRA_SUBJECT, "Send from Android");
mail.putExtra(Intent.EXTRA_TEXT, "Sent from Android");
startActivity(Intent.createChooser(mail,"Select Email Software..."));
What I would like to do is pre-select the email software and store it in a setting. That way, every time the email is being sent, it does not have to ask the user which email to use. I just can't seem to figure out how to invoke the chooser and get the selected value.
Any help would be greatly appreciated.
It's a common misconception to use text/plain or text/html. This will trigger any application that can handle plain or HTML text files without any context, including Google Drive, Dropbox, Evernote and Skype.
Instead use a ACTION_SENDTO, providing the mailto: Uri:
intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
You can then proceed using the chooser as suggested through the other answers.
Here is the solution:
private void setSpinnerValues() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
PackageManager pm = getPackageManager();
emailers = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_RESOLVED_FILTER);
if (emailers.size() == 0) {
spnEmailProgram.setEnabled(false);
return;
}
spnEmailProgram.setEnabled(true);
CharSequence[] sa = new CharSequence[emailers.size()];
int lastPosition = 0;
for (int i = 0; i < emailers.size(); i++) {
ResolveInfo r = emailers.get(i);
sa[i] = pm.getApplicationLabel(r.activityInfo.applicationInfo);
if (r.activityInfo.name.equalsIgnoreCase(Options.EmailClass)) {
lastPosition = i;
}
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, sa);
adapter.
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnEmailProgram.setAdapter(adapter);
spnEmailProgram.setSelection(lastPosition);
}
Save the choice for later use:
if (emailers.size() == 0) {
Options.EmailProgram = "";
Options.EmailClass = "";
} else {
ResolveInfo r = emailers.get(spnEmailProgram.getSelectedItemPosition());
Options.EmailProgram = r.activityInfo.packageName;
Options.EmailClass = r.activityInfo.name;
}
Now, to consume it, just to the following:
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("text/html");
Intent chooser = null;
if (Options.EmailProgram!=null && Options.EmailProgram.length()>0) {
mail.setClassName(Options.EmailProgram,Options.EmailClass);
chooser = mail;
}
fill in rest of data and start the activity
if (chooser == null) {
chooser = Intent.createChooser(mail,"Select Email Software...");
}
startActivity(chooser);
You would have to create your own chooser, possibly as an AlertDialog populated using the results of calling queryIntentActivities() on PackageManager.

Categories

Resources