如何使用ShareCompat.IntentBuilder启动活动

16

我正在尝试添加一个共享意图,以便在Google Plus上发布内容,但似乎无法解决将新的ShareCompat.IntentBuilder(Android支持库类)传递给startActivity方法的问题。我开始使用这个例子。我的应用程序是使用Android 2.2平台编译的。是否可能有另一种支持方式来启动Activity以启动共享意图。

IntentBuilder shareIntent = ShareCompat.IntentBuilder.from(MyActivity.this);                
shareIntent.setText(message);
shareIntent.setSubject(subject);

if (mFullFileName != null) {
    File imageFile = new File(mFullFileName);
    if (imageFile.exists()) {
        shareIntent.setStream(Uri.fromFile(imageFile));
        shareIntent.setType("image/jpeg");
    }
} else {
    shareIntent.setType("*.*");
}   
shareIntent.getIntent();
// doesn't compile only accepts Intent and not the Intentbuilder 
startActivity(shareIntent); 

你遇到了什么错误?如果可能的话,请提供logcat输出。 - havexz
抱歉..我的文章并不像我一开始想的那样准确..我在startActivity方法中添加了一个注释块..这是一个编译问题,似乎无法为我解决。 - user167698
3个回答

24

这是我的代码示例,但如果你需要一些参考资料,请点击超链接查看文章。

public void shareText(String text) {
        String mimeType = "text/plain";
        String title = "Example title";

        Intent shareIntent =   ShareCompat.IntentBuilder.from(this)
                                                    .setType(mimeType)
                                                    .setText(text)
                                                    .getIntent();
        if (shareIntent.resolveActivity(getPackageManager()) != null){
            startActivity(shareIntent);
        }
    }

关于ShareCompat.IntentBuilder 和 分享意图的博客文章


2
只是提供信息,您可以将 getIntent 替换为 createChooserIntent 以强制使用选择器。这样,您就不必检查包管理器是否能够解析活动,因为选择器会处理它。 - Big McLargeHuge
2
你在哪里使用了标题? - famfamfam

15

ShareCompat.IntentBuilder.from(ActivityName.this) 已经被弃用,请使用 IntentBuilder 的构造函数,如下所示:

Kotlin:

    ShareCompat
               .IntentBuilder(this@YourActivity)
               .setType("text/plain")
               .setChooserTitle("Share text with: ")
               .setText("Desired text to share")
               .startChooser()

Java:

new ShareCompat
                .IntentBuilder(YourActivity.this)
                .setType("text/plain")
                .setChooserTitle("Share text with: ")
                .setText("Desired text to share")
                .startChooser();

9
有趣的是,我刚刚明白了......给出的例子应该是创建一个Intent对象而不是IntentBuilder对象.. 我需要更改我的代码以链式创建对象。
Intent i = ShareCompat.IntentBuilder.from(MyActivity.this)
                       .setText(message)
                       .setSubject(subject)
                       .setStream(Uri.fromFile(imageFile))
                       .setType("image/jpeg")
                       .getIntent()
                       .setPackage("com.google.android.apps.plus");

您可以接受自己的答案...我删除了我的答案以减少噪音。 - havexz
1
请注意,Uri.fromFile(imageFile) 自 Nougat 版本(Android 7.0)以来已不安全。"传递文件:// URI 到包域之外可能会使接收者无法访问该路径。" https://developer.android.com/about/versions/nougat/android-7.0-changes.html#perm - Dmitry

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