Android和Facebook分享意图

Jos*_*ard 81 android facebook android-intent

我正在开发一个Android应用程序,我很想知道如何使用Android的共享意图从应用程序内更新应用程序用户的状态.

通过浏览Facebook的SDK看起来这很容易做到,但是我很想让用户通过常规的Share Intent弹出窗口来完成它吗?看到这里:

弹出

我尝试过通常的共享意图代码,但这似乎不适用于Facebook.

public void invokeShare(Activity activity, String quote, String credit) {
    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, activity.getString(R.string.share_subject));
    shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Example text");    

    activity.startActivity(Intent.createChooser(shareIntent, activity.getString(R.string.share_title)));
}
Run Code Online (Sandbox Code Playgroud)

更新:进行了更多的挖掘,看起来这是Facebook的应用程序的一个错误尚未解决!(facebook bug)对于平均时间,看起来我只能忍受负面的"分享不起作用!!!" 评论.干杯Facebook:*(

Jon*_*nik 109

显然Facebook不再(截至2014年)允许您自定义共享屏幕,无论您是打开sharer.php URL还是以更专业的方式使用Android意图.例如,请参阅以下答案:

无论如何,使用普通的Intent,您仍然可以共享一个URL,但不会billynomates所评论的那样共享任何默认文本.(此外,如果您没有要共享的URL,只需启动带有空"Write Post"(即状态更新)对话框的Facebook应用程序同样容易;请使用下面的代码但不要使用EXTRA_TEXT.)

这里是最好的解决办法,我发现,它没有使用任何的Facebook的SDK涉及.

此代码如果已安装,则直接打开官方Facebook应用程序,否则将回退到在浏览器中打开sharer.php.(这个问题中的大多数其他解决方案都提出了一个巨大的"使用......完成动作"对话框,这根本不是最佳选择!)

String urlToShare = "https://stackoverflow.com/questions/7545254";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "Foo bar"); // NB: has no effect!
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);

// See if official Facebook app is found
boolean facebookAppFound = false;
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
    if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) {
        intent.setPackage(info.activityInfo.packageName);
        facebookAppFound = true;
        break;
    }
}

// As fallback, launch sharer.php in a browser
if (!facebookAppFound) {
    String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
}

startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

(关于com.facebook.katana包名,请参阅MatheusJardimB的评论.)

在安装了Facebook应用的Nexus 7(Android 4.4)上,结果如下所示:

在此输入图像描述

  • "com.facebook.katana"是Facebook应用程序的包名称,"com.facebook.orca"是FB Messenger应用程序的包名称.你可以改成你想要的正确的pckg.如果你没有指定一个,第一个找到将被使用(不好) (3认同)
  • 最好的答案,谢谢!喜欢浏览器后备. (2认同)

Gök*_*ren 92

Facebook应用程序不处理EXTRA_SUBJECTEXTRA_TEXT字段.

这是错误链接:https://developers.facebook.com/bugs/332619626816423

谢谢@billynomates:

问题是,如果你在EXTRA_TEXT字段中放置一个URL ,它确实 有效.就像他们故意剥离任何文字一样.

  • 问题是,如果你在EXTRA_TEXT字段中放置一个URL,它*会起作用.就像他们故意剥离任何文字一样. (30认同)
  • 用户必须手动输入内容:"请注意,使用用户可以编辑的建议内容预填邮件参数也是违反政策的行为"https://www.youtube.com/watch?v=tGz48L0m5nc (2认同)

Mic*_*Bak 15

通常的方式

创建您要求的通常方法是简单地执行以下操作:

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, "The status update text");
    startActivity(Intent.createChooser(intent, "Dialog title text"));
Run Code Online (Sandbox Code Playgroud)

这对我没有任何问题.

替代方式(也许)

这样做的潜在问题是,您还允许通过电子邮件,短信等方式发送消息.以下代码是我在应用程序中使用的,允许用户向我发送电子邮件使用Gmail邮箱.我猜你可以尝试改变它以使其仅适用于Facebook.

我不确定它是如何响应任何错误或异常的(我猜想如果没有安装Facebook会发生这种情况),所以你可能需要对它进行一些测试.

    try {
        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        String[] recipients = new String[]{"e-mail address"};
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "E-mail subject");
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "E-mail text");
        emailIntent.setType("plain/text"); // This is incorrect MIME, but Gmail is one of the only apps that responds to it - this might need to be replaced with text/plain for Facebook
        final PackageManager pm = getPackageManager();
        final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
        ResolveInfo best = null;
        for (final ResolveInfo info : matches)
            if (info.activityInfo.packageName.endsWith(".gm") ||
                    info.activityInfo.name.toLowerCase().contains("gmail")) best = info;
                if (best != null)
                    emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
                startActivity(emailIntent);
    } catch (Exception e) {
        Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
    }
Run Code Online (Sandbox Code Playgroud)

  • @TomSusel是的,Facebook应该把他们的狗屎放在一起.但是在包含URL时它确实有效.谢谢你的downvote ;-) (4认同)
  • 谢谢您的回复.这让我很困惑,你发布的第一个代码片段适用于发布到其他具有可用分享意图的应用程序,但是有了Facebook的意图,它会将用户带到一个空白的"写东西"facebook页面,好像它没有发送一样(或可能接收)EXTRA_TEXT字段中的文本. (3认同)

Jem*_*rov 5

我发现您只能共享Text Image,而不能同时使用Intents. 如果存在,下面的代码仅共享图像,如果图像不存在则仅共享文本。如果您想共享两者,则需要从此处使用Facebook SDK。

如果您使用其他解决方案而不是下面的代码,请不要忘记指定包名称com.facebook.lite,这是Facebook Lite 的包名称。我还没有测试过,但如果你也想定位它,com.facebook.orcaFacebook Messenger 的包名。

您可以添加更多与WhatsAppTwitter共享的方法...

public class IntentShareHelper {

    /**
     * <b>Beware,</b> this shares only image if exists, or only text if image does not exits. Can't share both
     */
    public static void shareOnFacebook(AppCompatActivity appCompatActivity, String textBody, Uri fileUri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        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/*");
        }

        boolean facebookAppFound = false;
        List<ResolveInfo> matches = appCompatActivity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo info : matches) {
            if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana") ||
                info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.lite")) {
                intent.setPackage(info.activityInfo.packageName);
                facebookAppFound = true;
                break;
            }
        }

        if (facebookAppFound) {
            appCompatActivity.startActivity(intent);
        } else {
            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();
    }
}
Run Code Online (Sandbox Code Playgroud)

要从文件中获取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;
    }    
}
Run Code Online (Sandbox Code Playgroud)

要编写FileProvider,请使用此链接:https : //github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents


归档时间:

查看次数:

133776 次

最近记录:

7 年 前