13

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"));
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
user1966361
  • 179
  • 1
  • 3
  • 14
  • 1
    [This solution](http://stackoverflow.com/a/21186753/56285) fires up the official Twitter app directly if installed, or falls back to opening a chooser with other apps (e.g. browsers) capable of sending the tweet. – Jonik Jan 29 '14 at 08:09

5 Answers5

51

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.

soshial
  • 5,906
  • 6
  • 32
  • 40
sabadow
  • 5,095
  • 3
  • 34
  • 51
19

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.

Lukas Olsen
  • 5,294
  • 7
  • 22
  • 28
  • Thanks, this is useful! I know that there is a way of doing it with an intent that brings up the list of apps (twitter, fb, gmail etc) and twitter works, because I have seen it in other apps (Log Collector etc). I don't really want to have multiple buttons to share via mulitple apps :s – user1966361 Jan 14 '13 at 11:36
  • 2
    This doesn't answer the question, it simply provides a way of using Twitter to post the text. I am looking for the outcome of Twitter working to receive text when it comes up as an option under the Intent Action_Send. – user1966361 Jan 14 '13 at 16:05
  • thanks, dude, your answer was helpful , ignore hate comments – Zulqurnain Jutt Jul 02 '18 at 12:48
8

Try this, I used it and worked great

  Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/intent/tweet?text=...."));
  startActivity(browserIntent);         
Amt87
  • 5,493
  • 4
  • 32
  • 52
8

First you have to check if the twitter app installed on the device or not then share the text on twitter:

try
    {
        // Check if the Twitter app is installed on the phone.
        getActivity().getPackageManager().getPackageInfo("com.twitter.android", 0);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setClassName("com.twitter.android", "com.twitter.android.composer.ComposerActivity");
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "Your text");
        startActivity(intent);

    }
    catch (Exception e)
    {
        Toast.makeText(getActivity(),"Twitter is not installed on this device",Toast.LENGTH_LONG).show();

    }
Aboulfotoh
  • 153
  • 1
  • 9
3

For sharing text and image on Twitter, more controlled version of code is below, you can add more methods for sharing with WhatsApp, Facebook ... This is for official App and does not open browser if app not exists.

public class IntentShareHelper {

    public static void shareOnTwitter(AppCompatActivity appCompatActivity, String textBody, Uri fileUri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.setPackage("com.twitter.android");
        intent.putExtra(Intent.EXTRA_TEXT,!TextUtils.isEmpty(textBody) ? textBody : "");

        if (fileUri != null) {
            intent.putExtra(Intent.EXTRA_STREAM, fileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setType("image/*");
        }

        try {
            appCompatActivity.startActivity(intent);
        } catch (android.content.ActivityNotFoundException ex) {
            ex.printStackTrace();
            showWarningDialog(appCompatActivity, appCompatActivity.getString(R.string.error_activity_not_found));
        }
    }

    public static void shareOnWhatsapp(AppCompatActivity appCompatActivity, String textBody, Uri fileUri){...}

    private static void showWarningDialog(Context context, String message) {
        new AlertDialog.Builder(context)
                .setMessage(message)
                .setNegativeButton(context.getString(R.string.close), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(true)
                .create().show();
    }
}

For getting Uri from File, use below class:

public class UtilityFile {
    public static @Nullable Uri getUriFromFile(Context context, @Nullable File file) {
        if (file == null)
            return null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                return FileProvider.getUriForFile(context, "com.my.package.fileprovider", file);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return Uri.fromFile(file);
        }
    }

    // Returns the URI path to the Bitmap displayed in specified ImageView       
    public static Uri getLocalBitmapUri(Context context, ImageView imageView) {
        Drawable drawable = imageView.getDrawable();
        Bitmap bmp = null;
        if (drawable instanceof BitmapDrawable) {
            bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        } else {
            return null;
        }
        // Store image to default external storage directory
        Uri bmpUri = null;
        try {
            // Use methods on Context to access package-specific directories on external storage.
            // This way, you don't need to request external read/write permission.
            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();

            bmpUri = getUriFromFile(context, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmpUri;
    }    
}

For writing FileProvider, use this link: https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents

Community
  • 1
  • 1
Jemshit
  • 9,501
  • 5
  • 69
  • 106