如何在Android中自定义共享意图?

Zak*_*Zak 28 android share

现在我可以使用共享意图打开共享对话框

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, link);  
    startActivity(Intent.createChooser(intent, "Share with"));
Run Code Online (Sandbox Code Playgroud)

但我需要对话框不要出现并直接分享到一个社交网络(例如FB或Twitter)

任何建议如何做到这一点?

Der*_*rzu 81

有一种方法可以直接打开您想要的意图.您可以获取意图列表并仅打开一个意图.

看到这段代码:

private void initShareIntent(String type) {
    boolean found = false;
    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.setType("image/jpeg");

    // gets the list of intents that can be loaded.
    List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
    if (!resInfo.isEmpty()){
        for (ResolveInfo info : resInfo) {
            if (info.activityInfo.packageName.toLowerCase().contains(type) || 
                    info.activityInfo.name.toLowerCase().contains(type) ) {
                share.putExtra(Intent.EXTRA_SUBJECT,  "subject");
                share.putExtra(Intent.EXTRA_TEXT,     "your text");
                share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(myPath)) ); // Optional, just if you wanna share an image.
                share.setPackage(info.activityInfo.packageName);
                found = true;
                break;
            }
        }
        if (!found)
            return;

        startActivity(Intent.createChooser(share, "Select"));
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想打开twitter,那就这样做:

initShareIntent("twi");
Run Code Online (Sandbox Code Playgroud)

如果facebook:

initShareIntent("face");
Run Code Online (Sandbox Code Playgroud)

如果邮件:

initShareIntent("mail"); // or "gmail"
Run Code Online (Sandbox Code Playgroud)

如果你想显示一个与类型匹配的意图列表,请使用第一个马赫,请看这篇文章:Android Intent for Twitter应用程序


Kum*_*bek 8

不,你不能.Intent应该以这种方式工作.如果您必须强制打开特定应用,请在目标应用支持时使用显式意图.如果不知道目标应用程序的包名称或组件名称,或类型或mime类型的数据,则无法强制特定应用程序处理通用意图.

  • 你的意思是,对于Facebook例如我必须使用Facebook sdk并创建Facebook应用程序并链接我的Android应用程序,以便制作墙贴? (2认同)