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

5 回答 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 "";
    }
}

希望能帮助到你。

于 2013-01-14T11:24:16.840 回答
18

您只需打开带有文本的 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);

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

于 2013-01-14T11:24:08.137 回答
8

试试这个,我用过,效果很好

  Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/intent/tweet?text=...."));
  startActivity(browserIntent);         
于 2013-01-14T11:41:23.470 回答
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();

    }
于 2014-08-28T08:05:16.067 回答
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

于 2017-02-24T09:42:16.133 回答