Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I post on Twitter with Intent Action_send?

I have been struggling to send text from my app to Twitter.

The code below works to bring up a list of apps such as Bluetooth, Gmail, Facebook and Twitter, but when I select Twitter it doesn't prefill the text as I would have expected.

I know that there are issues around doing this with Facebook, but I must be doing something wrong for it to not be working with Twitter.

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Example Text");
startActivity(Intent.createChooser(intent, "Share Text"));
like image 553
user1966361 Avatar asked Jan 14 '13 11:01

user1966361


People also ask

How to share text on Twitter in Android programmatically?

you can simply open the URL with the text and Twitter App will do it. ;) String url = "http://www.twitter.com/intent/tweet?url=YOURURL&text=YOURTEXT"; Intent i = new Intent(Intent. ACTION_VIEW); i.


2 Answers

you can simply open the URL with the text and Twitter App will do it. ;)

String url = "http://www.twitter.com/intent/tweet?url=YOURURL&text=YOURTEXT";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

and it will also open the browser to login at the tweet if twitter app is not found.

like image 125
Lukas Olsen Avatar answered Sep 21 '22 08:09

Lukas Olsen


I'm using this snippet on my code:

private void shareTwitter(String message) {
    Intent tweetIntent = new Intent(Intent.ACTION_SEND);
    tweetIntent.putExtra(Intent.EXTRA_TEXT, "This is a Test.");
    tweetIntent.setType("text/plain");

    PackageManager packManager = getPackageManager();
    List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);

    boolean resolved = false;
    for (ResolveInfo resolveInfo : resolvedInfoList) {
        if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) {
            tweetIntent.setClassName(
                    resolveInfo.activityInfo.packageName,
                    resolveInfo.activityInfo.name);
            resolved = true;
            break;
        }
    }
    if (resolved) {
        startActivity(tweetIntent);
    } else {
        Intent i = new Intent();
        i.putExtra(Intent.EXTRA_TEXT, message);
        i.setAction(Intent.ACTION_VIEW);
        i.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + urlEncode(message)));
        startActivity(i);
        Toast.makeText(this, "Twitter app isn't found", Toast.LENGTH_LONG).show();
    }
}

private String urlEncode(String s) {
    try {
        return URLEncoder.encode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.wtf(TAG, "UTF-8 should always be supported", e);
        return "";
    }
}

Hope it helps.

like image 26
sabadow Avatar answered Sep 22 '22 08:09

sabadow