简体   繁体   中英

Open Facebook post in Facebook app

I want to include Facebook stories in my application, so that when a user clicks on the a post it opens up in Facebook's native app (if it existed). I have tried the below code but it seems very outdated

 Intent viewIntent;
        try {
            getActivity().getPackageManager().getPackageInfo("com.facebook.katana", 0);
            String uri = "fb://post/" + post.getId();
            viewIntent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(uri));
        } catch (Exception e) {
            String url = "https://www.facebook.com/" + PAGE_ID
                    + "/posts/" + post.getId;
            viewIntent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(url));
        }
        startActivity(viewIntent);

The uri you are using works only for older versions of facebook app. Use

public static String FACEBOOK_URL = "https://www.facebook.com/" + PAGE_ID
                + "/posts/" + post.getId;

//method to get the right URL to use in the intent
public String getFacebookPageURL(Context context) {
    PackageManager packageManager = context.getPackageManager();
    try {
        int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
        if (versionCode >= 3002850) { //newer versions of fb app
            return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
        } else { //older versions of fb app
            return "fb://post/" + post.getId();;
        }
    } catch (PackageManager.NameNotFoundException e) {
        return FACEBOOK_URL; //normal web url
    }
}

then

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = getFacebookPageURL(this);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);

thats all you need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM