13

アプリからTwitterにテキストを送信するのに苦労しています。

以下のコードは、Bluetooth、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);

また、Twitter アプリが見つからない場合は、ブラウザーを開いてツイートにログインします。

于 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 に答える