Open Facebook page from Android app?
Asked Answered
C

31

175

from my Android app, I would like to open a link to a Facebook profile in the official Facebook app (if the app is installed, of course). For iPhone, there exists the fb:// URL scheme, but trying the same thing on my Android device throws an ActivityNotFoundException.

Is there a chance to open a Facebook profile in the official Facebook app from code?

Crush answered 26/1, 2011 at 22:28 Comment(3)
There's a thread that doesn't have an answer on the facebook dev forums: forum.developers.facebook.net/viewtopic.php?pid=255227 (adding it here because it shows there's not an obvious answer, and maybe it'll get answered there someday...)Meyerhof
you can see my answer from here.Rajkot
It's always a big difficulty to load the FACEBOOK app directed to my page. The facebook support does not offer an easy support with a simple example code, besides changing the paths all the time. I decided to remove the facebook link from my apps.Baring
P
170

In Facebook version 11.0.0.11.23 (3002850) fb://profile/ and fb://page/ no longer work. I decompiled the Facebook app and found that you can use fb://facewebmodal/f?href=[YOUR_FACEBOOK_PAGE]. Here is the method I have been using in production:

/**
 * <p>Intent to open the official Facebook app. If the Facebook app is not installed then the
 * default web browser will be used.</p>
 *
 * <p>Example usage:</p>
 *
 * {@code newFacebookIntent(ctx.getPackageManager(), "https://www.facebook.com/JRummyApps");}
 *
 * @param pm
 *     The {@link PackageManager}. You can find this class through {@link
 *     Context#getPackageManager()}.
 * @param url
 *     The full URL to the Facebook page or profile.
 * @return An intent that will open the Facebook page/profile.
 */
public static Intent newFacebookIntent(PackageManager pm, String url) {
  Uri uri = Uri.parse(url);
  try {
    ApplicationInfo applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
    if (applicationInfo.enabled) {
      // https://mcmap.net/q/142232/-open-facebook-page-from-android-app
      uri = Uri.parse("fb://facewebmodal/f?href=" + url);
    }
  } catch (PackageManager.NameNotFoundException ignored) {
  }
  return new Intent(Intent.ACTION_VIEW, uri);
}
Parament answered 3/7, 2014 at 7:21 Comment(22)
@Malonis you should no longer use the ids. Just use the normal link.Parament
@JaredRummler edit your answer to open profile via idMalonis
I used your code and despite the fact that it open Facebook application I get the message "Page not found". What's wrong with my use? I know url is rightLowdown
I found it. You first have to change the username of your page if you haven't done it yet from here: www.facebook.com/usernameLowdown
@Malonis Just checked, working here. On Facebook version 13.0.0.13.14Parament
So you can't use the page id? I tried using the id instead of the name and it can't find the page in the app. the url seems fine because it resolves in the browser.Bursitis
It works as I am writing this comment, with the latest FB version.Mediator
You should use profile ID instead of name to open it. Anyone know which version code this Facebook app version was (or where to find it)? I would like to handle in the "old" way if the Facebook version is before that oneSearle
I take it back: the profile ID does not work there :/ and the version code is 3002850 isn't it?Searle
What do you replace ctx with?Centistere
@rhaphazard the activity or application context.Parament
What if i have only the facebook page_id rather than PageNameAbortion
This method is undocumented, hence unreliableBrumal
@AbdulWasae It has worked in apps with millions of downloads. If you have a better solution please post it instead of downvoting a working solution.Parament
It seems not working for now, @JaredRummler please check this. Currently FB app opens my feed instead of user profile pageGrano
@KonstantinKonopko What version of Facebook? I can't reproduce.Parament
@JaredRummler facebook-android-sdk:4.30.0Grano
can anyone confirm, that this still works? (as of June 2019). I still get ActivityNotFoundExceptionLombardy
I am also getting ActivityNotFoundException, tried different hrefsEpoch
This opens the facebook page but unlike regular fb pages , we don't see the Like button, profile and cover photos, etc. it directly opens the Contact info and displays all the posts from the page.Walking
anyone has a solution for the comment from @NeerajDwivedi? the issue is also here #37495677Dukie
This is showing "Trouble Loading, Tap to retry" screen in facebook appMuseum
P
238

This works on the latest version:

  1. Go to https://graph.facebook.com/<user_name_here> (https://graph.facebook.com/fsintents for instance)
  2. Copy your id
  3. Use this method:

    public static Intent getOpenFacebookIntent(Context context) {
    
       try {
        context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
        return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/<id_here>"));
       } catch (Exception e) {
        return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/<user_name_here>"));
       }
    }
    

This will open the Facebook app if the user has it installed. Otherwise, it will open Facebook in the browser.

EDIT: since version 11.0.0.11.23 (3002850) Facebook App do not support this way anymore, there's another way, check the response below from Jared Rummler.

Poach answered 18/4, 2012 at 15:59 Comment(17)
Thanks for this, helped me out greatly! Now if only there was a way to do it for twitterGoatfish
For a list of url schemes available on iOS see wiki.akosma.com/IPhone_URL_Schemes - some of them should work also on AndroidArsenate
this is taking me to browser of app , i want to open in my default page onlyDave
Facebook app is open with my app but it always display "Network Error"!Petticoat
You need to have the id of the page. not the username.Monosymmetric
With this approach I can open the desired page in my FB app, thanks for that. But then I face a problem, when I try to "Follow" or "Like" that page, it shows me a toast - "There was a problem following this Profile. Please try again later." I wonder why it could be happening. Any suggestion?Glary
& here's the answer of that issue; use "page" instead of profile - https://mcmap.net/q/144428/-cannot-see-like-option-in-facebook-page-from-android-deviceGlary
Just to note that fb://profile/ is NOT supported on Facebook app v1.3.2 which is included in stock Nexus One 2.3.6Alcorn
If you don't know the page id beforehand then this is a good solution: jaredrummler.com/2014/05/…Parament
@JaredRummler have you tried on the latest version of fb app ??Malonis
DjHacktorReborn is right, neither fb://profile/<fpid> nor fb://page/<fpid> are working anymore starting fb v11Male
@Malonis You are right. My bad. I decompiled the Facebook app and was able to come up with a workaround. Check out my answer below.Parament
@JaredRummler checked your answer its not working with fb id for a profileMalonis
Looks good with the latest Facebook app. It seems facebook has added back its support.Facer
@Poach what about <id here>? What I have, is fb page name, and app id. Is that (mentioned) id something else?Matroclinous
Hi, this still works for me in 2019, but in order to open the facebook app, we have to login to the facebook mobile app otherwise it will just bring us to the login activity of facebook.Selfanalysis
Working in 2020. and Opens the real facebook page, unlike other solutions opening the about section of the pagePancreatin
P
170

In Facebook version 11.0.0.11.23 (3002850) fb://profile/ and fb://page/ no longer work. I decompiled the Facebook app and found that you can use fb://facewebmodal/f?href=[YOUR_FACEBOOK_PAGE]. Here is the method I have been using in production:

/**
 * <p>Intent to open the official Facebook app. If the Facebook app is not installed then the
 * default web browser will be used.</p>
 *
 * <p>Example usage:</p>
 *
 * {@code newFacebookIntent(ctx.getPackageManager(), "https://www.facebook.com/JRummyApps");}
 *
 * @param pm
 *     The {@link PackageManager}. You can find this class through {@link
 *     Context#getPackageManager()}.
 * @param url
 *     The full URL to the Facebook page or profile.
 * @return An intent that will open the Facebook page/profile.
 */
public static Intent newFacebookIntent(PackageManager pm, String url) {
  Uri uri = Uri.parse(url);
  try {
    ApplicationInfo applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
    if (applicationInfo.enabled) {
      // https://mcmap.net/q/142232/-open-facebook-page-from-android-app
      uri = Uri.parse("fb://facewebmodal/f?href=" + url);
    }
  } catch (PackageManager.NameNotFoundException ignored) {
  }
  return new Intent(Intent.ACTION_VIEW, uri);
}
Parament answered 3/7, 2014 at 7:21 Comment(22)
@Malonis you should no longer use the ids. Just use the normal link.Parament
@JaredRummler edit your answer to open profile via idMalonis
I used your code and despite the fact that it open Facebook application I get the message "Page not found". What's wrong with my use? I know url is rightLowdown
I found it. You first have to change the username of your page if you haven't done it yet from here: www.facebook.com/usernameLowdown
@Malonis Just checked, working here. On Facebook version 13.0.0.13.14Parament
So you can't use the page id? I tried using the id instead of the name and it can't find the page in the app. the url seems fine because it resolves in the browser.Bursitis
It works as I am writing this comment, with the latest FB version.Mediator
You should use profile ID instead of name to open it. Anyone know which version code this Facebook app version was (or where to find it)? I would like to handle in the "old" way if the Facebook version is before that oneSearle
I take it back: the profile ID does not work there :/ and the version code is 3002850 isn't it?Searle
What do you replace ctx with?Centistere
@rhaphazard the activity or application context.Parament
What if i have only the facebook page_id rather than PageNameAbortion
This method is undocumented, hence unreliableBrumal
@AbdulWasae It has worked in apps with millions of downloads. If you have a better solution please post it instead of downvoting a working solution.Parament
It seems not working for now, @JaredRummler please check this. Currently FB app opens my feed instead of user profile pageGrano
@KonstantinKonopko What version of Facebook? I can't reproduce.Parament
@JaredRummler facebook-android-sdk:4.30.0Grano
can anyone confirm, that this still works? (as of June 2019). I still get ActivityNotFoundExceptionLombardy
I am also getting ActivityNotFoundException, tried different hrefsEpoch
This opens the facebook page but unlike regular fb pages , we don't see the Like button, profile and cover photos, etc. it directly opens the Contact info and displays all the posts from the page.Walking
anyone has a solution for the comment from @NeerajDwivedi? the issue is also here #37495677Dukie
This is showing "Trouble Loading, Tap to retry" screen in facebook appMuseum
B
39

Is this not easier? For example within an onClickListener?

try {
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/426253597411506"));
    startActivity(intent);
} catch(Exception e) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com/appetizerandroid")));
}

PS. Get your id (the large number) from http://graph.facebook.com/[userName]

Benghazi answered 24/6, 2013 at 23:4 Comment(2)
I agree, this is better because it does not make any assumptions about the Facebook app package name or intent filters. However, it is worse for the same reason because other apps might also specify matching intent filters. It depends what you want. Maybe add you do intent.setPackageName("com.facebook.katana") to make sure no other apps are called.Alcorn
But it opens the browser and there is shown Facebook data, how it is possible to use Facebook App (to call Facebook app) ?Adkisson
R
32

For Facebook page:

try {
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/" + pageId));
} catch (Exception e) {
    intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + pageId));
}

For Facebook profile:

try {
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + profileId));
} catch (Exception e) {
    intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + profileId));
}

...because none of the answers points out the difference

Both tested with Facebook v.27.0.0.24.15 and Android 5.0.1 on Nexus 4

Roee answered 19/2, 2015 at 14:1 Comment(6)
hi, how to know difference between profile and page?Biestings
Profile is for a private person, where a page is for companies, places, brands. See: facebook.com/help/217671661585622 [Title: How are Pages different from personal profiles?]Roee
for notes: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://note/" + facebookNoteId));Brythonic
To find Id for public page, event, profile you can use FindMyFbIdSweitzer
Profile is not opening up in Facebook App.Distended
but it is opening profile of logged in user, if we have different app_scoped_id then still it open logged in usersCanty
V
28

Here's the way to do it in 2016. It works great, and is very simple to use.

I discovered this after looking into how emails sent by Facebook opened the Facebook app.

// e.g. if your URL is https://www.facebook.com/EXAMPLE_PAGE, you should
// put EXAMPLE_PAGE at the end of this URL, after the ?
String YourPageURL = "https://www.facebook.com/n/?YOUR_PAGE_NAME";
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(YourPageURL));

startActivity(browserIntent);
Varicocele answered 14/5, 2016 at 21:40 Comment(5)
Works perfectly, even in 2016. Solves also an issue when you browse Facebook from Belgium (when cookies are disabled when not logged on).Carbylamine
When I use this, the header of the Facebook page I'm referencing is missing in the Facebook app, e.g. the page profile image and the Page / Activity / Insights tabs.Batholith
This works if you have the page name (as stated) but not if you have the numerical page ID.Uniplanar
Ok but does not bring me to a clean page where the user can make a like of my page easily.... Still looking for this ! Any solution ?Shutt
anyone have to solution for @Regis_AG ?Dukie
H
23

this is the simplest code for doing this

public final void launchFacebook() {
        final String urlFb = "fb://page/"+yourpageid;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(urlFb));

        // If a Facebook app is installed, use it. Otherwise, launch
        // a browser
        final PackageManager packageManager = getPackageManager();
        List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() == 0) {
            final String urlBrowser = "https://www.facebook.com/"+pageid;
            intent.setData(Uri.parse(urlBrowser));
        }

        startActivity(intent);
    }
Hazaki answered 21/5, 2013 at 16:57 Comment(4)
this is not working. when I am setting link "facebook.com/pages/"+pageid"Romp
Omit the 'pages/'-part ->use "facebook.com/" +pageIdRoee
still working as today ! thank you very much I changed this part ""facebook.com/pages/"+pageid;" with this one ""facebook.com/"+pageid;"Taenia
@naitbrahim Thank you for letting us know that it still working! I have edited the answer. btw, the answer was posted in 2013 :) Happy it helped youHazaki
D
14

A more reusable approach.

This is a functionality we generally use in most of our apps. Hence here is a reusable piece of code to achieve this.

(Similar to other answers in terms for facts. Posting it here just to simplify and make the implementation reusable)

"fb://page/ does not work with newer versions of the FB app. You should use fb://facewebmodal/f?href= for newer versions. (Like mentioned in another answer here)

This is a full fledged working code currently live in one of my apps:

public static String FACEBOOK_URL = "https://www.facebook.com/YourPageName";
public static String FACEBOOK_PAGE_ID = "YourPageName";

//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://page/" + FACEBOOK_PAGE_ID;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL; //normal web url
        }
    }

This method will return the correct url for app if installed or web url if app is not installed.

Then start an intent as follows:

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

That's all you need.

Daliladalis answered 2/1, 2016 at 9:25 Comment(1)
It threw "android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=fb://page/#### }"Favorable
F
10

To do this we need the "Facebook page id", you can get it :

  • from the page go to "About".
  • go to "More Info" section.

introducir la descripción de la imagen aquí

To opening facebook app on specified profile page,

you can do this:

 String facebookId = "fb://page/<Facebook Page ID>";
  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookId)));

Or you can validate when the facebook app is not installed, then open the facebook web page.

String facebookId = "fb://page/<Facebook Page ID>";
String urlPage = "http://www.facebook.com/mypage";

     try {
          startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookId )));
        } catch (Exception e) {
         Log.e(TAG, "Application not intalled.");
         //Open url web page.
         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlPage)));
        }
Felsite answered 10/5, 2017 at 16:50 Comment(2)
I didn't see this Page ID from the about tab. It is private?Dieldrin
@RoCkRoCk get it like so: curl -skA "Mozilla/5.0" https://www.facebook.com/mypage/ | grep -oE "fb://[^\"]+"Daylong
A
9

This has been reverse-engineered by Pierre87 on the FrAndroid forum, but I can't find anywhere official that describes it, so it's has to be treated as undocumented and liable to stop working at any moment:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("com.facebook.katana", "com.facebook.katana.ProfileTabHostActivity");
intent.putExtra("extra_user_id", "123456789l");
this.startActivity(intent);
Adult answered 27/1, 2011 at 8:13 Comment(2)
Yes, the solution has stopped to work. The error is: "java.lang.SecurityException?: Permission Denial: starting Intent { flg=0x10080000 cmp=com.facebook.katana/.ProfileTabHostActivity? (has extras) } from ProcessRecord?". Activity ProfileTabHostActivity has no android:exported flag in AndroidManifest, so by default android:exported="false" for this activity. As result ProfileTabHostActivity can't be launched by other applications. The only hope that FB developers will fix this problem in feature versions of FB application.Hijacker
i think the fix was to close this "accidental API".Corrosion
M
7

try this code:

String facebookUrl = "https://www.facebook.com/<id_here>";
        try {
            int versionCode = getPackageManager().getPackageInfo("com.facebook.katana", 0).versionCode;
            if (versionCode >= 3002850) {
                Uri uri = Uri.parse("fb://facewebmodal/f?href=" + facebookUrl);
                   startActivity(new Intent(Intent.ACTION_VIEW, uri));
            } else {
                Uri uri = Uri.parse("fb://page/<id_here>");
                startActivity(new Intent(Intent.ACTION_VIEW, uri));
            }
        } catch (PackageManager.NameNotFoundException e) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookUrl)));
        }
Murrain answered 23/1, 2015 at 7:44 Comment(0)
M
7

As of March 2020 this works perfectly.

private void openFacebookPage(String pageId) {
    String pageUrl = "https://www.facebook.com/" + pageId;

    try {
        ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo("com.facebook.katana", 0);

        if (applicationInfo.enabled) {
            int versionCode = getPackageManager().getPackageInfo("com.facebook.katana", 0).versionCode;
            String url;

            if (versionCode >= 3002850) {
                url = "fb://facewebmodal/f?href=" + pageUrl;
            } else {
                url = "fb://page/" + pageId;
            }

            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } else {
            throw new Exception("Facebook is disabled");
        }
    } catch (Exception e) {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(pageUrl)));
    }
}
Microwatt answered 27/3, 2020 at 16:19 Comment(1)
I was searching for a recent answer to this, thanks! Also I looked up that version where "fb://page/" is deprecated, and it's from 2014. Thus I honestly think it's safe to not have to include the earlier way to access the link.Sequestration
P
5

After much testing I have found one of the most effective solutions:

private void openFacebookApp() {
    String facebookUrl = "www.facebook.com/XXXXXXXXXX";
    String facebookID = "XXXXXXXXX";

    try {
        int versionCode = getActivity().getApplicationContext().getPackageManager().getPackageInfo("com.facebook.katana", 0).versionCode;

        if(!facebookID.isEmpty()) {
            // open the Facebook app using facebookID (fb://profile/facebookID or fb://page/facebookID)
            Uri uri = Uri.parse("fb://page/" + facebookID);
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
        } else if (versionCode >= 3002850 && !facebookUrl.isEmpty()) {
            // open Facebook app using facebook url
            Uri uri = Uri.parse("fb://facewebmodal/f?href=" + facebookUrl);
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
        } else {
            // Facebook is not installed. Open the browser
            Uri uri = Uri.parse(facebookUrl);
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
        }
    } catch (PackageManager.NameNotFoundException e) {
        // Facebook is not installed. Open the browser
        Uri uri = Uri.parse(facebookUrl);
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }
}
Pusey answered 15/9, 2015 at 7:12 Comment(0)
I
4

My answer builds on top of the widely-accepted answer from joaomgcd. If the user has Facebook installed but disabled (for example by using App Quarantine), this method will not work. The intent for the Twitter app will be selected but it will not be able to process it as it is disabled.

Instead of:

context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/620681997952698"));

You can use the following to decide what to do:

PackageInfo info = context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
if(info.applicationInfo.enabled)
    return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/620681997952698"));
else
    return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/620681997952698"));
Incurious answered 18/2, 2014 at 16:53 Comment(0)
K
4

Best answer I have found, it's working great.

Just go to your page on Facebook in the browser, right click, and click on "View source code", then find the page_id attribute: you have to use page_id here in this line after the last back-slash:

fb://page/pageID

For example:

Intent facebookAppIntent;
try {
    facebookAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/1883727135173361"));
    startActivity(facebookAppIntent);
} catch (ActivityNotFoundException e) {
    facebookAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://facebook.com/CryOut-RadioTv-1883727135173361"));
    startActivity(facebookAppIntent);
}
Kelcy answered 27/3, 2017 at 15:16 Comment(1)
This only make sense for static apps.Complete
C
3

You can check it for all Facebook Apps that any of Facebook apps are installed or not . For supporting OS level 11 we need to add this in AndrodiManifest.xml to avoid package name not found exception -

<manifest ...
<queries>
    <package android:name="com.facebook.katana" />
    <package android:name="com.facebook.lite" />
    <package android:name="com.facebook.android" />
    <package android:name="com.example.facebook" />
</queries>
 <application .....

Then add this method to you code -

public static String isFacebookAppInstalled(Context context){

        if(context!=null) {
            PackageManager pm=context.getPackageManager();
            ApplicationInfo applicationInfo;

            //First check that if the main app of facebook is installed or not
            try {
                applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
                return applicationInfo.enabled?"com.facebook.katana":"";
            } catch (Exception ignored) {
            }

            //Then check that if the facebook lite is installed or not
            try {
                applicationInfo = pm.getApplicationInfo("com.facebook.lite", 0);
                return applicationInfo.enabled?"com.facebook.lite":"";
            } catch (Exception ignored) {
            }

            //Then check the other facebook app using different package name is installed or not
            try {
                applicationInfo = pm.getApplicationInfo("com.facebook.android", 0);
                return applicationInfo.enabled?"com.facebook.android":"";
            } catch (Exception ignored) {
            }

            try {
                applicationInfo = pm.getApplicationInfo("com.example.facebook", 0);
                return applicationInfo.enabled?"com.example.facebook":"";
            } catch (Exception ignored) {
            }
        }
        return "";
    }

And then launch the app -

if (!TextUtils.isEmpty(isFacebookAppInstalled(context))) {
 /* Facebook App is installed,So launch it. 
  It will return you installed facebook app's package
  name which will be useful to launch the app */

  Uri uri = Uri.parse("fb://facewebmodal/f?href=" + yourURL);
 Intent intent = context.getPackageManager().getLaunchIntentForPackage(isFacebookAppInstalled(context);
                if (intent != null) {
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(uri);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
                else {
                    Intent intentForOtherApp = new Intent(Intent.ACTION_VIEW, uri);
                    context.startActivity(intentForOtherApp);
                } 
 }
Churchill answered 17/3, 2021 at 11:18 Comment(2)
Unfortunately it didn't work for me with the call via katana, always open facebook on my own profile, but never on the indicated page.Baring
@Baring I'm doing R&D on this topic as I also facing it. After finishing I will edit this question. Thank you.Churchill
U
2
Intent intent = null;
    try {
        getPackageManager().getPackageInfo("com.facebook.katana", 0);
        String url = "https://www.facebook.com/"+idFacebook;
        intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href="+url));
    } catch (Exception e) {
        // no Facebook app, revert to browser
        String url = "https://facebook.com/"+idFacebook;
        intent = new Intent(Intent.ACTION_VIEW);
        intent .setData(Uri.parse(url));
    }
    this.startActivity(intent);
Underdone answered 15/12, 2016 at 2:14 Comment(0)
P
2

As of July 2018 this works perfectly with or without the Facebook app on all the devices.

private void goToFacebook() {
    try {
        String facebookUrl = getFacebookPageURL();
        Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
        facebookIntent.setData(Uri.parse(facebookUrl));
        startActivity(facebookIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private String getFacebookPageURL() {
    String FACEBOOK_URL = "https://www.facebook.com/Yourpage-1548219792xxxxxx/";
    String facebookurl = null;

    try {
        PackageManager packageManager = getPackageManager();

        if (packageManager != null) {
            Intent activated = packageManager.getLaunchIntentForPackage("com.facebook.katana");

            if (activated != null) {
                int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

                if (versionCode >= 3002850) {
                    facebookurl = "fb://page/1548219792xxxxxx";
                }
            } else {
                facebookurl = FACEBOOK_URL;
            }
        } else {
            facebookurl = FACEBOOK_URL;
        }
    } catch (Exception e) {
        facebookurl = FACEBOOK_URL;
    }
    return facebookurl;
}
Prothrombin answered 2/8, 2018 at 6:54 Comment(6)
FB Lite app has a separate package name, if you use this way then you should also check com.facebook.lite -- though I have not checked if Lite will handle these URLCommit
@Commit I don't have FB Lite. It would be good to know whether the code works with it. If you could test it somehow and put your findings here, that would help others who still come here. Appreciated, thanksProthrombin
@Prothrombin --> Yourpage-1548219792xxxxxx in the url is the page id or page url. So for ex: facebook.com/PageName is my page url and the id is something like 2345676. So the URL to mention in the code will be facebook.com/PageName or something else?Walking
@NeerajDwivedi You need both: your page name and page ID in the URL. Something like this: 'String FACEBOOK_URL = "facebook.com/BeanRoaster-1548219792112345/";'Prothrombin
@Prothrombin i have used the exact same code replacing the FACEBOOK_URL to "facebook.com/myPageName-myPageID" and i'm getting a blank page with Search bar at top. I'm using latest Facebook app on Android 9 (Fb app version - 237.0.0.44.120)Walking
@NeerajDwivedi I just tried it on an Android 9 Samsung and it works fine. Check the page name and ID again. I know it sounds silly, but I cannot think of anything else. Or, try to copy your URL from the code and paste it in the address bar of a browser to see if it works.Prothrombin
L
2

To launch facebook page from your app, let urlString = "fb://page/your_fb_page_id"

To launch facebook messenger let urlString = "fb-messenger://user/your_fb_page_id"

FB page id is usually numeric. To get it, goto Find My FB ID input your profile url, something like www.facebook.com/edgedevstudio then click "Find Numberic ID".

Voila, you now have your fb numeric id. replace "your_fb_page_id" with the generated Numeric ID

 val intent = Intent(Intent.ACTION_VIEW, Uri.parse(urlString))
 if (intent.resolveActivity(packageManager) != null) //check if app is available to handle the implicit intent
 startActivity(intent)
Leannleanna answered 10/8, 2018 at 11:49 Comment(0)
H
2

Declare constants

  private String FACEBOOK_URL="https://www.facebook.com/approids";
    private String FACEBOOK_PAGE_ID="approids";

Declare Method

public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

            boolean activated =  packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
            if(activated){
                if ((versionCode >= 3002850)) {
                    Log.d("main","fb first url");
                    return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
                } else {
                    return "fb://page/" + FACEBOOK_PAGE_ID;
                }
            }else{
                return FACEBOOK_URL;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL;
        }
    }

Call Function

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
                String facebookUrl = getFacebookPageURL(MainActivity.this);
                facebookIntent.setData(Uri.parse(facebookUrl));
                startActivity(facebookIntent);
Hodgkins answered 28/9, 2019 at 8:29 Comment(0)
K
2

Check out my code for opening Facebook specific Page:

//ID initialization
ImageView facebook = findViewById(R.id.facebookID);

facebook.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String facebookId = "fb://page/327031464582675";
            String urlPage = "http://www.facebook.com/MDSaziburRahmanBD";

            try {
               startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookId)));
            }catch (Exception e){
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlPage)));
            }
        }
    });
Klondike answered 28/12, 2020 at 3:7 Comment(0)
F
1

I have created a method to open facebook page into facebook app, if app is not existing then opening in chrome

    String socailLink="https://www.facebook.com/kfc";
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String facebookUrl = Utils.getFacebookUrl(getActivity(), socailLink);
    if (facebookUrl == null || facebookUrl.length() == 0) {
        Log.d("facebook Url", " is coming as " + facebookUrl);
        return;
    }
    intent.setData(Uri.parse(facebookUrl));
    startActivity(intent);

Utils.class add these method

public static String getFacebookUrl(FragmentActivity activity, String facebook_url) {
    if (activity == null || activity.isFinishing()) return null;

    PackageManager packageManager = activity.getPackageManager();
    try {
        int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
        if (versionCode >= 3002850) { //newer versions of fb app
            Log.d("facebook api", "new");
            return "fb://facewebmodal/f?href=" + facebook_url;
        } else { //older versions of fb app
            Log.d("facebook api", "old");
            return "fb://page/" + splitUrl(activity, facebook_url);
        }
    } catch (PackageManager.NameNotFoundException e) {
        Log.d("facebook api", "exception");
        return facebook_url; //normal web url
    }
}

and this

 /***
 * this method used to get the facebook profile name only , this method split domain into two part index 0 contains https://www.facebook.com and index 1 contains after / part
 * @param context contain context
 * @param url contains facebook url like https://www.facebook.com/kfc
 * @return if it successfully split then return "kfc"
 *
 * if exception in splitting then return "https://www.facebook.com/kfc"
 *
 */
 public static String splitUrl(Context context, String url) {
    if (context == null) return null;
    Log.d("Split string: ", url + " ");
    try {
        String splittedUrl[] = url.split(".com/");
        Log.d("Split string: ", splittedUrl[1] + " ");
        return splittedUrl.length == 2 ? splittedUrl[1] : url;
    } catch (Exception ex) {
        return url;
    }
}
Forsook answered 19/10, 2016 at 13:46 Comment(2)
In the latest version, this is actually taking me to the about page while I am looking to navigate to home page. Any tips ?Mahmud
Have you found the solution??Septic
S
1

open fb on button click event without using facebook sdk

 Intent FBIntent = new Intent(Intent.ACTION_SEND);
    FBIntent.setType("text/plain");
    FBIntent.setPackage("com.facebook.katana");
    FBIntent.putExtra(Intent.EXTRA_TEXT, "The text you wanted to share");
    try {
        context.startActivity(FBIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(context, "Facebook have not been installed.", Toast.LENGTH_SHORT).show( );
    }
Scissor answered 28/1, 2019 at 9:24 Comment(0)
L
1

1-to get your id go to your image profile and click right click and take copy link adress.

        try {
                Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("fb://profile/id"));
                startActivity(intent);
            } catch(Exception e) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("facebook url")));
            }
        }
    });
Lazar answered 25/8, 2019 at 16:10 Comment(0)
T
1

To open the Facebook page in Facebook app from your Webview add this code in your shouldOverrideUrlLoading method

if (url.startsWith("https://www.facebook.com || Your Facebook page address")) {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" + url)));
                } catch (Exception e2) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                }
                return true;
            }
Terenceterencio answered 15/3, 2022 at 14:3 Comment(0)
W
0

Answering this in October 2018. The working code is the one using the pageID. I just tested it and it is functional.

public static void openUrl(Context ctx, String url){
    Uri uri = Uri.parse(url);
    if (url.contains(("facebook"))){
        try {
            ApplicationInfo applicationInfo = ctx.getPackageManager().getApplicationInfo("com.facebook.katana", 0);
            if (applicationInfo.enabled) {
                uri = Uri.parse("fb://page/<page_id>");
                openURI(ctx, uri);
                return;
            }
        } catch (PackageManager.NameNotFoundException ignored) {
            openURI(ctx, uri);
            return;
        }
    }
Wyrick answered 30/10, 2018 at 15:14 Comment(0)
B
0

I implemented in this form in webview using fragment- inside oncreate:

 webView.setWebViewClient(new WebViewClient()
{
    public boolean shouldOverrideUrlLoading(WebView viewx, String urlx)
                {
     if(Uri.parse(urlx).getHost().endsWith("facebook.com")) {
                        {
                            goToFacebook();
                        }
                        return false;
                    }
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlx));
                    viewx.getContext().startActivity(intent);
                    return true;
                }

});

and outside onCreateView :

 private void goToFacebook() {
        try {
            String facebookUrl = getFacebookPageURL();
            Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
            facebookIntent.setData(Uri.parse(facebookUrl));
            startActivity(facebookIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //facebook url load
    private String getFacebookPageURL() {
        String FACEBOOK_URL = "https://www.facebook.com/pg/XXpagenameXX/";
        String facebookurl = null;

        try {
            PackageManager packageManager = getActivity().getPackageManager();

            if (packageManager != null) {
                Intent activated = packageManager.getLaunchIntentForPackage("com.facebook.katana");

                if (activated != null) {
                    int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

                    if (versionCode >= 3002850) {
                        facebookurl = "fb://page/XXXXXXpage_id";
                    }
                } else {
                    facebookurl = FACEBOOK_URL;
                }
            } else {
                facebookurl = FACEBOOK_URL;
            }
        } catch (Exception e) {
            facebookurl = FACEBOOK_URL;
        }
        return facebookurl;
    }
Blackpool answered 19/12, 2018 at 18:7 Comment(0)
G
0
fun getOpenFacebookIntent(context: Context, url: String) {
    return try {
        context.packageManager.getPackageInfo("com.facebook.katana", 0)
        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/$url/")))
    } catch (e: Exception) {
        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
    }
}
Galop answered 21/8, 2019 at 6:37 Comment(0)
A
0

Answer worked for me but one missing thing was to add query in manifest, here is my solution:

private void openFacebookApp() {
String facebookUrl = "www.facebook.com/XXXXXXXXXX";
String facebookID = "XXXXXXXXX";

try {
    int versionCode = getActivity().getApplicationContext().getPackageManager().getPackageInfo("com.facebook.katana", 0).versionCode;

    if(!facebookID.isEmpty()) {
        // open the Facebook app using facebookID (fb://profile/facebookID or fb://page/facebookID)
        Uri uri = Uri.parse("fb://page/" + facebookID);
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    } else if (versionCode >= 3002850 && !facebookUrl.isEmpty()) {
        // open Facebook app using facebook url
        Uri uri = Uri.parse("fb://facewebmodal/f?href=" + facebookUrl);
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    } else {
        // Facebook is not installed. Open the browser
        Uri uri = Uri.parse(facebookUrl);
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }
} catch (PackageManager.NameNotFoundException e) {
    // Facebook is not installed. Open the browser
    Uri uri = Uri.parse(facebookUrl);
    startActivity(new Intent(Intent.ACTION_VIEW, uri));
}

}

and add that in Manifest outside the application tag

    <queries>
    <package android:name="com.google.android.gm" />
    <package android:name="com.facebook.katana" />
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="https" />
    </intent>
    <intent>
        <action android:name="android.intent.action.DIAL" />
        <data android:scheme="tel" />
    </intent>
    <intent>
        <action android:name="android.intent.action.SEND" />
        <data android:mimeType="*/*" />
    </intent>
</queries>
Accede answered 12/10, 2021 at 21:51 Comment(0)
N
0

I have been trying all of these methods with no luck because the ID... to find the one that works for my profile and for any profile you must go to the profile you want to open without been logged in (sorry for my english), inspect the page (in chrome Ctrl+Shift+I or just F12), and look for the line that holds the attribute al:android:url, the profile id should be there...

enter image description here

... And then:

    public static void OpenFacebookProfile(String profileID, String username)
{
    boolean isFacebookInstalled = 
            null != PA.getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
    
    Intent intent = isFacebookInstalled ?
            new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + profileID)) :
            new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + username));
    
    PA.startActivity(intent);
}
Neumeyer answered 8/1, 2023 at 7:44 Comment(0)
B
-1
try {
       String[] parts = url.split("//www.facebook.com/profile.php?id=");
       getPackageManager().getPackageInfo("com.facebook.katana", 0);
       startActivity(new Intent (Intent.ACTION_VIEW, Uri.parse(String.format("fb://page/%s", parts[1].trim()))));
    } catch (Exception e) {
       startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }
Benghazi answered 9/9, 2017 at 17:56 Comment(1)
Please post an explanation of your code. See How to AnswerFelsite
R
-2

You can open the facebook app on button click as follows:-

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            startNewActivity("com.facebook.katana");
        }
    });

}

public void startNewActivity( String packageName)
{
    Intent intent = MainActivity.this.getPackageManager().getLaunchIntentForPackage(packageName);
    if (intent != null)
    {
        // we found the activity
        // now start the activity
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    else
    {
        // bring user to the market
        // or let them choose an app?
        intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id="+packageName));
        startActivity(intent);
    }
}
Resource answered 25/2, 2014 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.