如何使用Intent Action_send在Twitter上发布内容?

13

我一直在努力将文本从我的应用程序发送到Twitter。

下面的代码可以显示出蓝牙、Gmail、Facebook和Twitter等应用程序列表,但当我选择Twitter时,它没有像我预期的那样填充文本。

我知道在Facebook上做这个有问题,但是我的操作必须有问题才导致它无法在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"));

1
如果官方 Twitter 应用已安装,则 此解决方案 将直接启动该应用程序,否则将打开带有其他可发送推文的应用程序选择器(例如浏览器)。 - Jonik
5个回答

51
我正在使用以下代码片段:

在我的代码中:

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 "";
    }
}

希望这有所帮助。

2
这种方法的问题在于它只允许使用官方Twitter应用程序。 - StackOverflowed
@StackOverflowed 但我相信只有少数经常使用 Twitter 的用户没有安装该应用程序,以至于他们会分享内容。 - Sheychan
这段代码会抛出安全异常:在 Twitter 上分享时权限被拒绝。 - prince_sachdeva

19

您只需打开带有文本的URL,Twitter应用程序将自动处理。;)

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);

如果未找到Twitter应用程序,它还将打开浏览器以登录到推文。


谢谢,这很有用!我知道有一种方法可以通过意图来打开应用程序列表(Twitter、FB、Gmail等),而且Twitter是可以工作的,因为我在其他应用程序(Log Collector等)中看到过。我不想要多个按钮来通过多个应用程序分享:s - user1966361
2
这并没有回答问题,只是提供了一种使用Twitter发布文本的方法。我正在寻找Twitter在Intent Action_Send选项下接收文本的结果。 - user1966361
谢谢,伙计,你的回答很有帮助。请忽略恶意评论。 - Zulqurnain Jutt

8

试一下这个,我用过它,效果非常好。

  Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/intent/tweet?text=...."));
  startActivity(browserIntent);         

8

首先,您需要检查设备上是否安装了Twitter应用程序,然后分享文本到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();

    }

此代码在分享到 Twitter 时抛出了安全异常:权限拒绝。 - prince_sachdeva
它不再起作用了..请尝试这个链接: https://dev59.com/fHjZa4cB1Zd3GeqPfZDp#49692442 - iMobaio

3

以下是更精细控制的代码,适用于在Twitter上分享文本图片。您可以添加更多的分享方法,如WhatsAppFacebook等。此代码适用于官方应用程序,如果应用程序不存在,不会打开浏览器。

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();
    }
}

要从文件中获取Uri,请使用以下类:

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;
    }    
}

要编写 FileProvider,请使用此链接:https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接