简体   繁体   中英

Can I get Twitter API response in my Android app any other way than with onNewIntent() method?

I don't have much experience with development in Android. I am working on app, which can communicate with Facebook, Twitter, LinkedIn and Google+.

Every social network has own wrapper, which handles communication between Android app and social network. Facebook communication is already done. I have problems with Twitter communication. Implemetations, which I have found on internet use twitter4j library and internet browser for logging. Then you must read response data from browser.

For example this: Twitter Test App

My issue is reading this response data from browser. Logging and authorizing in browser goes without problems. Tutorials like I mentioned above use usually onNewIntent() Activity method for dealing with browser response. But I cannot use this method, because it is used for different purposes. I don't know if it's posible to do this without any other Activity apart from MainActivity or I need to create another Activity in wrapper, which will handle whole Twitter communication.

Thanks for any help.

I'm really not sure why so many examples for twitter4j on the internet go through intents and custom schemes to handle the callback URL. I find this awkward for most scenarios. I also dislike leaving the application to go to the browser to login.

Instead, try using a WebView to load the page. Then you can attach a WebViewClient which can detect the callback URL. You won't have to deal with changing the manifest, etc. too. You might do something like this, perhaps inside onCreateView in a DialogFragment :

mWebView = new WebView(context);
mWebView.setWebViewClient(new WebViewClient() {
    @Override
    public void onLoadResource(WebView view, String url) {
        if (url.startsWith(CALLBACK_URL)) {
            Uri uri = Uri.parse(url);
            String denied = uri.getQueryParameter("denied");
            if (denied != null) {
                // handle denied
            } else {
                // handle authenticated
            }
        }
        super.onLoadResource(view, url);
    }
});

and then you can load the authentication URL in onViewCreated (if you're doing this in a DialogFragment ):

    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    RequestToken reqToken = twitter.getOAuthRequestToken();
    mWebView.loadUrl(reqToken.getAuthenticationURL());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM