Twitter4j OAuth callback succeeds, but test tweet fails - android

Having a rough time with OAuth in Twitter4j. Before this, I had the problem detailed in #3255153 and a 401 error, but finally fixed those, and ran into a harder to solve problem.
The Twitter application authorization page launches in a browser, I log in, and approve the application for my account. It then redirects back to the application, and nothing happens. The view is the exact same as before launching the authorization page.
To see if it had worked, I have it set to Toast a message saying "Login to Twitter Successful", in either onResume or onNewIntent (shown below), which never pops. The successful callback URL is received, however, as this entry shows up in LogCat:
12-18 09:25:50.426: I/ActivityManager(186): Starting: Intent { act=android.intent.action.VIEW cat=[android.intent.category.BROWSABLE] dat=snapp://twitter?oauth_token=tokenhere&oauth_verifier=verifierhere cmp=com.infini_servers.snapp/.SnappActivity } from pid 7853
Here's my onNewIntent (also have a virtual clone for onResume):
#Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(CALLBACKURL))
{
Toast.makeText(getBaseContext(), "Login to twitter successful!", Toast.LENGTH_LONG);
String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try
{
provider.retrieveAccessToken(consumer, verifier);
AccessToken accessToken = new AccessToken(consumer.getToken(),
consumer.getTokenSecret());
twitter.setOAuthConsumer(consumerKey, consumerSecret);
twitter.setOAuthAccessToken(accessToken);
String tweet = "Test";
twitter.updateStatus(tweet);
Toast.makeText(getBaseContext(), "Tweet Successful!", Toast.LENGTH_LONG);
}
catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG);
}
}
}
And the relevant bits of my Manifest:
<activity
android:label="#string/app_name"
android:name=".SnappLaunch" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/app_name"
android:name=".SnappActivity"
android:launchMode="singleInstance" >
<intent-filter >
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="snapp" android:host="twitter" />
</intent-filter>
</activity>

I've recently been playing with Twitter4j and had some problems that sound similar to those you are experiencing. I can't see anything wrong in the code you've posted, but I wonder what the callback URL you're passing to getOauthRequestToken is? I had some issues with this myself. I think your CALLBACKURL needs to be set to "snapp://twitter". Note that you need the colon.
If that doesn't work, I suggest you try removing the android:host from the manifest line:
<data android:scheme="snapp" android:host="twitter" />
so you're left with:
<data android:scheme="snapp" />
and then in the code where you make the call to getOauthRequestToken, pass the value "snapp:///". This was basically what I did to first get it working.
If this then works, you could try experimenting with putting the android:host="twitter" back and then changing the value passed to getOauthRequestToken.
If this doesn't work, have you seen if the onNewIntent is called at all - i.e. is it just not passing the uri.toString().startsWith(CALLBACKURL) test as your toast is only displayed if that passes? You could try putting some logging in or add a break point in the debugger.

Toast.makeText(getBaseContext(), "Login to twitter successful!", Toast.LENGTH_LONG);
Don't forget to call 'show()' when you want to make a toast.

your onResume() method code put into inside of asynctask. its working fine.
see that sample,
class TwitterLogin extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL))
{
String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
// Shared Preferences
Editor e = loginPrefs.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit();
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("UserID: ", "userID: "+userID+""+username);
Log.v("Welcome:","Thanks:"+Html.fromHtml("<b>Welcome " + username + "</b>"));
}
catch (Exception e)
{
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
}

Related

Firebase user: isEmailVerified returns false

I'm developing an Android app that uses Firebase Authentication. After creating a new user, I'm sending a verification email.
Firebase.auth.currentUser?.let {user ->
user.sendEmailVerification().addOnCompleteListener {verificationTask ->
if(verificationTask.isSuccessful){
_verificationSuccess.value = true
} else {
_verificationError.value = verificationTask.exception
}
}
}
In my manifest, I added an Intent filter that opens my app when the user tries to open the verification link.
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="test-project.firebaseapp.com"
android:scheme="https"/>
</intent-filter>
The problem is that, when the link opens my app, the email is not verified. I have this validation that always returns false
if(Firebase.auth.currentUser.isEmailVerified){
//Email verified
} else {
throw Exception("Email not verified")
}
Only when the verification link is opened in the web explorer, the validation returns true. How can I verify the email inside my app?
By applying the intent filter you have, you've told Android that you will handle all web requests that target https://test-project.firebaseapp.com. Now that your application has trapped browsing to this URL, you now need to make the request to the server on the user's behalf.
By default, when you send an email verification off to the user, they will receive an email with a link that looks like:
https://<PROJECT_ID>.firebaseapp.com/__/auth/action?mode=verifyEmail&oobCode=<VERIFICATION_CODE>&apiKey=<API_KEY>&lang=<LANGUAGE>
Note: These links can be customized using custom action handlers or you could make use of dynamic links so that you don't intercept everything headed for https://test-project.firebaseapp.com.
Because a user may wish to visit your app's website in a browser, you should make your intent filter more specific to just handling email actions.
<intent-filter android:label="#string/filter_view_handle_action_code">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https"
android:host="test-project.firebaseapp.com"
android:pathPrefix="/__/auth/action" />
</intent-filter>
Disclaimer: I haven't tested if the below method works, but in theory it should.
If you intercept such a URL, you need to handle it in the onCreate method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = this.getIntent();
if (intent.hasCategory(android.intent.category.BROWSABLE)) {
// intent came from browser
Uri data = intent.getData();
String mode = data.getQueryParameter("mode");
String oobCode = data.getQueryParameter("oobCode");
if (mode != "verifyEmail" || oobCode == null) {
Log.i("MyActivity", "Started with unexpected browsable intent");
return;
}
handleVerifyEmailActionCode(oobCode);
}
}
private handleVerifyEmailActionCode(String oobCode) {
String email = null;
FirebaseAuth.getInstance().checkActionCode(oobCode)
.onSuccessTask( actionCodeResult -> {
if (actionCodeResult.getOperation() != ActionCodeResult.VERIFY_EMAIL) {
throw new UnsupportedActionCodeOperationException(actionCodeResult.getOperation());
}
email = actionCodeResult.getInfo().getEmail();
return FirebaseAuth.getInstance().applyActionCode(oobCode);
})
.addOnCompleteListener( applyActionCodeTask -> {
if (!applyActionCodeTask.isSuccessful()) {
Exception ex = applyActionCodeTask.getException();
// TODO: Handle exceptions
Toast.makeText(getApplicationContext(), "Failed to verify email. " + ex.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
// email verified successfully!
// do something interesting
Toast.makeText(getApplicationContext(), email + " was verified!", Toast.LENGTH_SHORT).show();
FirebaseUser user = FirebaseAuth.getCurrentUser(); // WARN: May not have finished initializing yet?
if (user != null && user.getEmail() == email) {
user.reload()
.addOnFailureListener(ex -> {
Log.e(MyActivity.class, "Failed to refresh user token: " + ex.getMessage());
});
} else {
Log.i(
MyActivity.class,
user == null
? "User wasn't signed in, skipping reload"
: "User email mismatch, skipping reload"
);
}
});
}
/**
* Custom exception to be used when a OOB code's `ActionCodeResult.Operation`
* doesn't match what it was expected to be.
*
* #see https://firebase.google.com/docs/reference/android/com/google/firebase/auth/ActionCodeResult#constant-summary
*/
public class UnsupportedActionCodeOperationException extends Exception {
protected int operation;
public UnsupportedActionCodeOperationException(int operation) {
super("The ActionCodeResult.Operation value of " + operation + " is not supported");
this.operation = operation;
}
public int getOperation() {
return this.operation;
}
}

onNewIntent is never gets called - Android

I am trying to create a simple oauth2 flow using AppAuth. I am following this tutorial of AppAuth. It is doing good up to making an oauth request but after authorization when it comes to main activity then it never calls onNewIntent, I also checked the question discussed here.
Edit: When I use onResume method then it comes to onResume method after authorization but with "android.intent.action.MAIN" action. Where it should come with "com.google.codelabs.appauth.HANDLE_AUTHORIZATION_RESPONSE" action on onResume.
Any suggestion why it is happening?
following is the MainActivity class
public class MainActivity extends AppCompatActivity {
private static final String USED_INTENT = "USED_INTENT";
public static final String LOG_TAG = "AppAuthSample";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void setupAuthorization(View view) {
AuthorizationServiceConfiguration serviceConfiguration = new AuthorizationServiceConfiguration(
Uri.parse("https://accounts.google.com/o/oauth2/v2/auth"), //* auth endpoint *//*,
Uri.parse("https://oauth2.googleapis.com/token") //* token endpoint *//*
);
String clientId = "MY_ID.apps.googleusercontent.com";
Uri redirectUri = Uri.parse("com.demo.testdriveapi:/oauth2callback");
AuthorizationRequest.Builder builder = new AuthorizationRequest.Builder(
serviceConfiguration,
clientId,
"code",
redirectUri
);
builder.setScopes("https://www.googleapis.com/auth/drive.appdata");
AuthorizationRequest request = builder.build();
AuthorizationService authorizationService = new AuthorizationService(this);
String action = "com.google.codelabs.appauth.HANDLE_AUTHORIZATION_RESPONSE";
Intent postAuthorizationIntent = new Intent(action);
PendingIntent pendingIntent = PendingIntent.getActivity(this, request.hashCode(), postAuthorizationIntent, 0);
authorizationService.performAuthorizationRequest(request, pendingIntent);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
checkIntent(intent);
}
private void checkIntent(#Nullable Intent intent) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case "com.google.codelabs.appauth.HANDLE_AUTHORIZATION_RESPONSE":
if (!intent.hasExtra(USED_INTENT)) {
handleAuthorizationResponse(intent);
intent.putExtra(USED_INTENT, true);
}
break;
default:
// do nothing
}
}
}
#Override
protected void onStart() {
super.onStart();
checkIntent(getIntent());
}
private void handleAuthorizationResponse(#NonNull Intent intent) {
AuthorizationResponse response = AuthorizationResponse.fromIntent(intent);
AuthorizationException error = AuthorizationException.fromIntent(intent);
final AuthState authState = new AuthState(response, error);
if (response != null) {
Log.i(LOG_TAG, String.format("Handled Authorization Response %s ", authState.jsonSerializeString()));
AuthorizationService service = new AuthorizationService(this);
service.performTokenRequest(response.createTokenExchangeRequest(), new AuthorizationService.TokenResponseCallback() {
#Override
public void onTokenRequestCompleted(#Nullable TokenResponse tokenResponse, #Nullable AuthorizationException exception) {
if (exception != null) {
Log.w(LOG_TAG, "Token Exchange failed", exception);
} else {
if (tokenResponse != null) {
authState.update(tokenResponse, exception);
Log.i(LOG_TAG, String.format("Token Response [ Access Token: %s, ID Token: %s ]", tokenResponse.accessToken, tokenResponse.idToken));
}
}
}
});
}
}
}
Here is the snippet from AndroidMenifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="com.google.codelabs.appauth.HANDLE_AUTHORIZATION_RESPONSE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity android:name="net.openid.appauth.RedirectUriReceiverActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="com.demo.testdriveapi"/>
</intent-filter>
</activity>
</application>
and here is the snippet of activity_main.xml, I only have one button
<Button
android:id="#+id/buttonAuthorize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="153dp"
android:layout_marginTop="288dp"
android:layout_marginEnd="170dp"
android:onClick="setupAuthorization"
android:text="Authorize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Edit: Also tried using "android:launchMode="singleTop" but it also doesn't work.
Edit2: Adding screenshot of Google developer console
check the google drive API Dashboard for oAuth authentication and your callback name shall match and it should be registered there as well. And it is with this callback that authorization response is sent back to your activity.
It appears that net.openid:appauth:0.7.1 is buggy. I stumbled upon this question then I changed my version to 0.2.0 and it worked.
If I understand you correctly, you have successfully configured AppAuth and on launching the authentication mechanism, the user is able to enter their username and password to login into openId or whatever it is. But on doing so you cannot intercept the result of that intent (chrome custom tabs).
If so try this override method
onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
you also need to startActivityForResult(authIntent, REQUEST_CODE)

Android redirect uri

I'm working with the instagram API and I don't understand what I should put in for the redirect api. At the moment I simply put in https://127.0.0.1
But I dont really understand. Also, once I get the allow/cancel screen and I press allow it gives me an error saying that I cant go to that address but I can also see the authorization code appended on to the address. So how can i redirect back from my redirect uri? How can I tell android that after user clicks allow to come back into the app use the code for further authentication?
Im sure you will say something like make my own custom scheme/ intent filters etc but please be a little more supportive im new and I dont understand and I did do research on them.
My on resume method is below
#Override
protected void onResume() {
super.onResume();
// the intent filter defined in AndroidManifest will handle the return from ACTION_VIEW intent
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(redirectUri)) {
// use the parameter your API exposes for the code (mostly it's "code")
String code = uri.getQueryParameter("code");
if (code != null) {
// get access token
LoginService loginService =
ServiceGenerator.createService(LoginService.class, clientId, clientSecret);
AccessToken accessToken = loginService.getAccessToken(code, "authorization_code");
} else if (uri.getQueryParameter("error") != null) {
// show an error message here
}
}
}
This is my manifest snippet dealing with intent filters:
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="redirecturi"
android:scheme="your" />
</intent-filter>
</activity>
You have to setup an event listener on the browser view and check for code in URL param if the URL is equal to the redirect_uri, and then make POST request to the auth URL using the code and client_secret as documented in Instagram authentication
something like this:
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
String code = url.getQueryParameter("code");
// ...
}
});

Twitter login redirecting to wrong activiy

im trying to log in to twitter with this example:
http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/
My problem is that after the log in the browser is done. Its redirecting to my main activity and not to the
activity from where i called the log in method. Because of that i dont get the user
AccessToken from the user.
This is from my manifest:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="oauth" android:host="t4jsample"/>
</intent-filter>
My log in method:
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())), TWITER);
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
My callback URL
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
Thanks for helping :)
I had the same problem.
What I did was :
1 - Uninstall sample app from http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/
2 - Add
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="oauth" android:host="t4jsample"/>
</intent-filter>
In the manifest, in the activity you want to get back.
(You might keep the sample app, but change the data android:host="t4jsample" to other string).
Hope it helps!
I'm not sure because I never integerated with twitter api.
but I think you should start an intent after you get the auth.
Intent i = new intent(reditectedActivity.class, thisActivity.this);
startActivity(i);
so it's like this
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())), TWITER);
Intent i = new intent(reditectedActivity.class, thisActivity.this);
startActivity(i);
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
or in the main activity you can do ..
first define this
static final String TWITTER_CALLBACK_URL = null;
then
if (!TWITTER_CALLBACK_URL == nul){
Intent i = new intent(mainactivity.this, whereIsTheLogin.class);
startActivity(i);
}

How to check callback_url in twitter application

i have loads of examples for O_Auth but no one is working properly and i guess the only thing is callback URL in every example, I am getting 401 error like consumer key or signature didn't match. I already seen so many examples on 401 the only thing that goes into my favor is my callback url.
android app cannot connect to twitter.
Getting 401 when requesting access token with signpost within android with-signpost-within-android
Android Dev - Callback URL not working... (0_o)
I already seen all these examples and many more.
But still i am not getting my point, If at the time of application form i use http://www.meomyo.com at callback url, Then what should i use it in my coding
like android:scheme="?" android:host="?"
currrently i am using other examples callbacks
//private static final Uri CALLBACK_URI = Uri.parse("bloa-app://twitt");
private static final Uri CALLBACK_URI = Uri.parse("twitterapp://connect");
i have consumer key as well secret key, but in case of callback url i am stuck on it.
If anyone want i can provide my consumer as well secret key.
public class OAuth extends Activity {
private static final String APP = "OAUTH";
private Twitter twitter;
private OAuthProvider provider;
private CommonsHttpOAuthConsumer consumer;
private String CONSUMER_KEY = "Xh3o8Gh1JQnklkUnTvvA";
private String CONSUMER_SECRET = "SCLy6yoUSth53goAsYYkoqR4ZuBoaInyJXsm5PQR11I";
private String CALLBACK_URL = "merabharatmahan://piyush";
private TextView tweetTextView;
private Button buttonLogin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tweetTextView = (TextView)findViewById(R.id.tweet);
buttonLogin = (Button)findViewById(R.id.ButtonLogin);
buttonLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
askOAuth();
}
});
}
/**
* Open the browser and asks the user to authorize the app.
* Afterwards, we redirect the user back here!
*/
private void askOAuth() {
try {
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
provider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
Log.e(APP, e.getMessage());
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
/**
* As soon as the user successfully authorized the app, we are notified
* here. Now we need to get the verifier from the callback URL, retrieve
* token and token_secret and feed them to twitter4j (as well as
* consumer key and secret).
*/
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try {
// this will populate token and token_secret in consumer
provider.retrieveAccessToken(consumer, verifier);
// TODO: you might want to store token and token_secret in you app settings!!!!!!!!
AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
// create a tweet
Date d = new Date(System.currentTimeMillis());
String tweet = "#OAuth working! " + d.toLocaleString();
// send the tweet
twitter.updateStatus(tweet);
// feedback for the user...
tweetTextView.setText(tweet);
Toast.makeText(this, tweet, Toast.LENGTH_LONG).show();
buttonLogin.setVisibility(Button.GONE);
} catch (Exception e) {
Log.e(APP, e.getMessage());
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
manifest code is
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".OAuth"
android:label="#string/app_name"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="merabharatmahan" android:host="piyush" />
</intent-filter>
</activity>
</application
now i am getting communication with the service provider is failed: Received Authentication challenge is null. It is the simplest example that i put here.
twitterapp://connect is your call back url.
In Android manifest.xml define your activity like this:
<activity android:name=".auth.SocialNetworkActivity"
android:configChanges="orientation"
android:label="Connect SNS" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="twitterapp" android:host="connect" />
</intent-filter>
</activity>
Now, it will open twitter web page, and on successful authentication, your activities onNewIntent() callback method will be called.
In above example, use your own activity name.
Apart from that, twitter integration in my application is done using twitter4j.
You must put whatever you think will be unique:
android:scheme="name-of-your-dog" android:host="something-else"
Oh, wait... maybe there's someone else owning a dog called like yours... so, use the package name of your app:
android:scheme="com.your.package" android:host="something-else"
And, if it's not working for you... I don't think it's related to the callback URL. How are you declaring your activity in the manifest? You added the android:launchMode="singleTask" parameter, right?
And, as the zombie guy pointed out, you must handle the callback in the onNewIntent method of your auth activity. Something like this:
final Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals("name-of-your-dog")) {
//etc...
}

Categories

Resources