Android 我如何在Twitter上发布您发送的意向行动?

Android 我如何在Twitter上发布您发送的意向行动?,android,android-intent,twitter,share,Android,Android Intent,Twitter,Share,我一直在努力从我的应用程序向Twitter发送文本 下面的代码可以显示蓝牙、Gmail、Facebook和Twitter等应用程序的列表,但当我选择Twitter时,它不会像我预期的那样预先填充文本 我知道在Facebook上这样做会有一些问题,但我一定是做错了什么,因为它没有在Twitter上工作 Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Inten

我一直在努力从我的应用程序向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"));

您只需用文本打开URL,Twitter应用程序即可完成此操作。;)


如果找不到twitter应用程序,它还会打开浏览器登录推特。

我在代码中使用了以下代码片段:

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 "";
    }
}
private void shareTwitter(字符串消息){
意向tweetIntent=新意向(Intent.ACTION\u SEND);
tweetIntent.putExtra(Intent.EXTRA_文本,“这是一个测试”);
tweetIntent.setType(“文本/普通”);
PackageManager packManager=getPackageManager();
List resolvedInfoList=packManager.querytentActivities(仅限tweetIntent、PackageManager.MATCH_DEFAULT_);
布尔值=假;
对于(ResolveInfo ResolveInfo:resolvedInfoList){
if(resolveInfo.activityInfo.packageName.startsWith(“com.twitter.android”)){
tweetIntent.setClassName(
resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name);
已解决=正确;
打破
}
}
如果(已解决){
星触觉(tweetIntent);
}否则{
意图i=新意图();
i、 putExtra(Intent.EXTRA_文本、消息);
i、 设置动作(意图、动作和视图);
i、 setData(Uri.parse(“https://twitter.com/intent/tweet?text=“+urlEncode(message));
星触觉(i);
Toast.makeText(此“未找到Twitter应用程序”,Toast.LENGTH_LONG.show();
}
}
私有字符串urlEncode(字符串s){
试一试{
返回URLEncoder.encode(s,“UTF-8”);
}捕获(不支持的编码异常e){
Log.wtf(标签“应始终支持UTF-8”,e);
返回“”;
}
}

希望能有帮助。

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

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

首先,您必须检查设备上是否安装了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上共享文本和图像,下面是更受控制的代码版本,您可以添加更多与共享的方法。。。这是用于官方应用程序,如果应用程序不存在,则不会打开浏览器

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

要编写文件提供程序,请使用以下链接:

谢谢,这很有用!我知道有一种方法可以让你列出应用程序列表(twitter、fb、gmail等),twitter也可以工作,因为我在其他应用程序(Log Collector等)中也看到过。我真的不想通过多个应用程序共享多个按钮:这并不能回答这个问题,它只是提供了一种使用Twitter发布文本的方式。我正在寻找Twitter接收文本的结果,当它作为意向行动_Send下的一个选项出现时。谢谢,伙计,你的回答很有帮助,忽略仇恨评论。这种方法的问题是,它只允许官方Twitter应用程序。@StackOverflow,但我相信只有很少的用户经常使用Twitter,应用程序未达到共享内容的程度。此代码引发安全异常:拒绝在Twitter上共享的权限。如果已安装,则直接启动官方Twitter应用程序,或者使用其他能够发送推文的应用程序(如浏览器)打开选择器。此代码引发安全异常:拒绝在Twitter上共享权限。它不再工作。请尝试以下操作:
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;
    }    
}