I'm working on a backend platform for a client in which he can add users and their twitter username. The frontend is an android/ios application in which the app's users can open a twitter app intent.
For android it seems to be that the code is the following:
int userId;
try {
getPackageManager().getPackageInfo("com.twitter.android", 0);
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("twitter://user?user_id="+userId));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} catch (Exception e) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/"+userId));
}
this.startActivity(intent);
So It seems that I NEED to use the user id instead of the username.
So I was wondering if there is any way to make a POST/GET request to twitter in order to get a username's user_id, if possible enconded in JSON format.
Found the solution
Uri.parse("twitter://user?screen_name="+username)
Related
I'm using the oauth2-essentials library because it was one of the recommended oauth libraries on the uber developers site, and it has been recently updated.
My code looks like this:
executor = new HttpUrlConnectionExecutor();
OAuth2AuthorizationProvider provider = new BasicOAuth2AuthorizationProvider(
URI.create("https://login.uber.com/oauth/v2/authorize"),
URI.create("https://login.uber.com/oauth/v2/token"),
new Duration(1,0,3600) /* default expiration time in case the server doesn't return any */);
OAuth2ClientCredentials credentials = new BasicOAuth2ClientCredentials(
getString(R.string.uberClientId), getString(R.string.uberSecret));
uberOAuthClient = new BasicOAuth2Client(
provider,
credentials,
new LazyUri(new Precoded("my redirect url")) /* Redirect URL */);
generateUberOAuthToken("my phone number", "my password");
}
public void generateUberOAuthToken(final String uName, final String password){
new Thread() {
public void run() {
try {
uberOAuthToken = new ResourceOwnerPasswordGrant(
uberOAuthClient, new BasicScope("profile"), uName, password).accessToken(executor);
}
catch (Exception e){
e.printStackTrace();
}
}
}.start();
}
The exception: org.dmfs.httpessentials.exceptions.UnauthorizedException: Authentication at 'https://login.uber.com/oauth/v2/token' failed. is always thrown. I've tried removing the redirect url so it should use the default from my dashboard, and I've tried added 1 and/or dashes to the phone number. The exception is always thrown when I request an access token. I know my account is setup correctly because this works fine in iOS. I feel like I must be missing something obvious. Anyone else run into this issue?
The token api did not recognize my phone number as a valid login parameter. It worked when I used my email instead.
Note: This issue only arises when the Facebook app is installed.
I'm trying to open a user's Facebook profile page when an ImageButton is clicked. After looking at this suggested method for more recent Facebook app versions, it's mostly working, with the exception of users that are friends with the logged in user (in the app), or the logged in user themselves.
The process is:
Image button is clicked
Call to Facebook Graph API is made to get the link to the user's profile via their Facebook ID (stored in our database)
A new Intent is created by checking to see if the Facebook app is installed, and generating the correct Uri
A new Activity is started with the generated Intent
Because we're using Facebook Graph API v2.0, the username field is removed from the GraphUser object in the JSON. The problem is that the Facebook link (GraphUser.getLink()) is either:
An app-scoped (protected) link if the user (logged into the app) is not friends with the user whose profile we are trying to view; format is : https://www.facebook.com/app_scoped_user_id/{protected-id}
A 'normal' Facebook link with the user's real id (unprotected); format is: http://www.facebook.com/{real-user-id}
The real problem is that the Facebook Uri when the app is installed expects either:
An app-scoped link
A link with the username attached to it, not {user-id}
However, the web version (opened in a web view) doesn't care. The link can be app-scoped, username-based or id-based. So everything works for WebViews.
Since username is completely inaccessible in Graph API v2.0, I'm just getting null values, which means that for the Facebook app I can't generate the correct Uri that it expects (username-based), only id-based or app-scoped.
Here is the code that I'm using to create the Intent:
public static Intent getFacebookIntent(String facebookProfileUrl) {
PackageManager pm = App.getContext().getPackageManager();
Uri uri;
try {
pm.getPackageInfo("com.facebook.katana", 0);
uri = Uri.parse("fb://facewebmodal/f?href=" + facebookProfileUrl);
} catch (PackageManager.NameNotFoundException e) {
uri = Uri.parse(facebookProfileUrl);
}
return new Intent(Intent.ACTION_VIEW, uri);
}
And here is my onClick() method on the ImageButton:
new Request(
Session.getActiveSession(),
String.valueOf(mate.getFacebookId()),
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
GraphUser g = response.getGraphObjectAs(GraphUser.class);
String fbUrl = g.getLink();
// TODO: If link does not contain 'scoped', need USERNAME, not ID
String otherUrl = "https://www.facebook.com/" + myAppUser.getId();
String finalUrl = (fbUrl.contains("scoped")) ? fbUrl : otherUrl;
Intent intent = getFacebookIntent(finalUrl);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
).executeAsync();
I need the username if the app is installed, otherwise the web view deals with it as it should.
So the question: How can I get a Facebook username by id for the Facebook app? Or, is there a different Uri that the Facebook app expects that I can account for, using ids and not usernames?
You should be able to use the fb://profile/{user-id} URL format to launch native apps. This will let you use the user ID instead of a username. You could rewrite your getFacebookIntent method as:
public Intent getFacebookIntent(GraphUser user) {
PackageManager pm = this.getPackageManager();
Uri uri;
try {
pm.getPackageInfo("com.facebook.katana", 0);
uri = Uri.parse("fb://profile/" + user.getId());
} catch (PackageManager.NameNotFoundException e) {
uri = Uri.parse(user.getLink());
}
return new Intent(Intent.ACTION_VIEW, uri);
}
You could then call this method and pass in the GraphUser object.
I want to know how to send app request to all my facebook friends from android app. I tried in graph API. But, couldn't get it done.
https://graph.facebook.com/apprequests?ids=friend1,friend2&message='Hi'&method=post&access_token=ACCESS_TOKEN
I know this is a Duplicate question. But, couldn't find an answer yet.
I'm getting this error on the above API.
"All users in param ids must have accepted TOS."
I hope there will be a way to send app request to all friends from mobile on a click. Please share it.
The error message you receive ("All users in param ids must have accepted TOS") is because you are trying to send an app generated request to a user who is not connected to your app.
See the developer docs here.
Requests sent with the request dialog and app generated requests are different and you can't use app generated requests to invite users to your app.
Sending Facebook app requests are not available via the graph api. You can use the app requests java-script dialog to send the request though, you would just need to specify the user's id in the "to" property as detailed in the documentation.
Sample function:
<script>
FB.init({ appId: '**appId**', status: true, cookie: true, xfbml : true });
function sendRequest(to) {
FB.ui({method: 'apprequests', to: to, message: 'You should learn more about this awesome site.', data: 'tracking information for the user'});
return false;
}
</script>
Then just wire an onclick for each image to something like onclick="return sendRequest('**friendId**');"
Also you can call this function in javascript: It will give you all friends with photos. Also group of friends who are currently using same app. You can send request to any of them.
function sendRequestViaMultiFriendSelector() {
FB.ui({
method: 'apprequests',
message: "You should learn more about this awesome site."
});
}
See Facebook Friend Request - Error - 'All users in param ids must have accepted TOS'
Have you seen demo of "Hackbook" in the developer.facebook.com ?
You can refer HACKBOOK APP REQUEST FROM HERE.
You can achieve to post the app request to only one friend by below code.
Code:
Bundle params = new Bundle();
JSONObject attachment = new JSONObject();
JSONObject properties = new JSONObject();
JSONObject prop1 = new JSONObject();
JSONObject prop2 = new JSONObject();
JSONObject media = new JSONObject();
JSONStringer actions = null;
try {
attachment.put("name", "YOUR_APP");
attachment.put("href", "http://www.google.com/");
attachment.put("description", "ANY_TEXT");
media.put("type", "image");
media.put("src", "IMAGE_LINK");
media.put("href", "http://www.google.com/");
attachment.put("media", new JSONArray().put(media));
prop1.put("text", "www.google.com");
prop1.put("href", "http://www.google.com");
properties.put("Visit our website to download the app", prop1);
/* prop2.put("href", "http://www.google.com");
properties.put("iTunes Link ", prop2);*/
attachment.put("properties", properties);
Log.d("FACEBOOK", attachment.toString());
actions = new JSONStringer().object()
.key("name").value("APP_NAME")
.key("link").value("http://www.google.com/").endObject();
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("ACTIONS STRING: "+actions.toString());
System.out.println("ATTACHMENT STRING: "+attachment.toString());
params.putString("actions", actions.toString());
params.putString("attachment", attachment.toString()); // Original
params.putString("to", "YOUR_FRIEND_FACEBOOK_ID");
Utility.mFacebook.dialog(getParent(), "stream.publish", params,new PostDialogListener());
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getApplicationContext(), ""+getResources().getString(R.string.facebook_response_msg_posted), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), ""+getResources().getString(R.string.facebook_response_msg_not_posted), Toast.LENGTH_SHORT).show();
}
}
}
Above code works perfect if you want to post the Apprequest only on One friend's wall. If you want to post on all then you have to make asynckTask which runs for all the friends post and post App request on all walls.
Update
Here is the link in PHP that have done same work to send request to all Facebook friends.
And [here it is clearly explained3 that it is blocked by Facebook to send a Friend Request to more then 15-20 friends.
Now, you have to only one option to do it is, use above code in AsyncTask to send Friend Request to all Friends One-by-One.
I need to obtain OAuth2 authentication token to pass it to the server so it can fetch list of Google Reader feeds for the user. Server is .NET - I have no access to it or to it's code but most likely it is using unofficial Reader API
I was able to use Android Account manager to obtain valid token for this purpose with the following code (notice that authTokenType="reader")
Account account = accounts[0];
manager.getAuthToken(account, "reader", null, this, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
// If the user has authorized your application to use the tasks API
// a token is available.
String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
// Now you can send the token to API...
cacheManager.putString(GOOGLE_AUTH, token);
GoogleReaderManager.startAddFeedActivity(AddGoogleReaderSourcesActivity.this);
finish();
} catch (OperationCanceledException e) {
Log.e(TAG, "User cancelled", e);
finish();
} catch (Exception e) {
Log.e(TAG, "Failed to obtain Google reader API_KEY", e);
}
}
}, null);
The code above works fine when I send token to the server side .Net app: the app is able to retrieve the list of Reader feeds.
The problem is that this only works for "Google inside" devices. On Nook I have no such luck since there's no way that I was able to find to add Google account to the account manager. So I'm trying to it using OAuth 2 protocol as described here
It works fine as far as obtaining the token: User approves the app from the mobile page which returns the code token which then mobile app exchanges for the Auth token. However this token will not work with the server process. I have a feeling that perhaps I'm using the wrong scope in this URL:
https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.google.com/reader/api/0/subscription/list&redirect_uri=http://localhost&approval_prompt=force&state=/ok&client_id={apps.client.id}
Scopes that I did try in various combinations:
https://www.google.com/reader/api
https://www.google.com/reader/api/0
https://www.google.com/reader/api/0/subscription/list
https://www.google.com/reader/api+https://www.google.com/reader/atom
Here's example of JSON that is returned from get token POST
{"expires_in":3600,
"token_type":"Bearer",
"access_token":"ya29.AHES6ZSEvuUb6Bvd2DNoMnnN_UnfxirZmf_RQjn7LptFLfI",
"refresh_token":"1\/bUwa5MyOtP6VyWqaIEKgfPh08LNdawJ5Qxz6-qZrHg0"}
Am I messing up scope or token type? Not sure how to change a token type. Any other ideas?
P.S. Google account login page asks: Manage your data in Google Reader, that's why I suspect that the scope is wrong
I got it working for https://www.google.com/reader/api/0/subscription/list. So thought of sharing with you.
I have valid access_token:
This is what i tried to resolve it (partially) :
Google provides OAuth 2.o playgound; where they actually simulate all aspects of OAuth 2.0 as well as final API call to fetch data.
I found this very helpful as it clearly shows what is being sent to request.
Here is the URL : https://developers.google.com/oauthplayground/
Using this, i tweaked my api call below and it works :)
public static String getReaderContent(String accessToken){
String url = "https://www.google.com/reader/api/0/subscription/list" ;
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(url);
String response="";
method.setRequestHeader("Authorization", "OAuth "+accessToken);
try {
int statusCode = client.executeMethod(method);
String response= method.getResponseBodyAsString();
System.out.println("response " + responseStr);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
So this works properly fine for getting subscription list; but have not been able to make it work for reader api which you have mentioned in your question.
Let me know if you have got way around google reader API.
I am new to integrating Twitter. I have implemented Twitter in my application with this code:
// Create file
File picture = new File(APP_FILE_PATH + "/myAwesomeDrawing.png");
// Create TwitPic object and allocate TwitPicResponse object
TwitPic tpRequest = new TwitPic("username", "password");
TwitPicResponse tpResponse = null;
// Make request and handle exceptions
try {
tpResponse = tpRequest.uploadAndPost(picture, "Image Uploaded from My AndroidDrawing App...");
}
catch (IOException e) {
e.printStackTrace();
}
catch (TwitPicException e) {
e.printStackTrace();
}
// If we got a response back, print out response variables
if(tpResponse != null)
tpResponse.dumpVars();
All works fine here. But here I have to add the username and password programmatically. Is there any other way to use the Twitter integration as like Facebook OAuth to integration?
I need to know how Twitter OAuth is checked, and if the User is not login then it will ask for the username and password in its in built window.
If caguilar187's code link's are not enough, then here are few more links for code help:
http://blog.doityourselfandroid.com/2011/08/08/improved-twitter-oauth-android/
http://blog.doityourselfandroid.com/2011/02/13/guide-to-integrating-twitter-android-application/
http://marakana.com/forums/android/examples/312.html
Best suggested: http://android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application
One more suggest: http://automateddeveloper.blogspot.com/2011/06/android-twitter-oauth-authentication.html
Post on Twitter: http://www.londatiga.net/it/how-to-post-twitter-status-from-android/
GitHub Link: https://github.com/brione/Brion-Learns-OAuth
Hope below link help you:-
Below link show you how to generate key with Twitter and other social media
http://code.google.com/p/socialauth-android/wiki/Twitter
Now below link is source code where u find out source code
http://code.google.com/p/socialauth-android/downloads/list
here are a few they all use signpost to do it.
Signpost:
http://code.google.com/p/oauth-signpost/
Blogs
http://dev.bostone.us/2009/07/16/android-oauth-twitter-updates/#awp::2009/07/16/android-oauth-twitter-updates/
http://blog.copyninja.info/2010/09/android-oauth-authentication-with.html
http://code.google.com/p/oauth-signpost/wiki/TwitterAndSignpost