- Использование API Graph для Android
- Предварительные требования
- Класс GraphRequest
- Доступ к данным пользователя
- Обработка результатов
- Обработка ошибок
- Устранение неполадок
- Пакетные запросы
- Integrating the Facebook Graph API in Android
- Create Project and Set up SDK
- Logging in
- Getting and Sharing data to Facebook
- Conclusion
- Graph API Reference
- Graph API Root Nodes
- Graph API Root Edges
- Facebook SDK for Android
- Common Uses
- Documentation Contents
- Component SDKs
- Getting Started
- Calling the Graph API from Android
- FAQ & Troubleshooting
- Changelog
- Upgrade Guide
- Devices
- Reference
- Downloads
- Deprecated
Использование API Graph для Android
Android SDK поддерживает интеграцию с Facebook API Graph. Классы GraphRequest и GraphResponse позволяют отправлять запросы и получать ответы в формате JSON в асинхронном режиме. Кроме того, класс GraphRequestBatch позволяет отправлять серверам Facebook пакетные запросы, которые обрабатываются за один цикл.
Подробнее об API Graph см. в разделах:
См. также справочные материалы по GraphRequest , GraphResponse и GraphRequestBatch . Вы узнаете, как использовать Facebook SDK для Android и создавать вызовы API Graph для дополнительных сценариев.
Предварительные требования
Класс GraphRequest
В классе GraphRequest есть метод newMeRequest . Он вызывает эндпойнт /user/me, чтобы извлечь данные пользователя для указанного маркера доступа.
Android SDK отправляет все разрешения, указанные в access_token , тем самым обеспечивая контроль доступа к данным. Если у приложения нет маркера доступа, API Graph возвращает только общедоступную информацию. Подробнее о свойствах и разрешениях User см. в разделе Справка по API Graph: User .
По умолчанию метод newMeRequest извлекает из объекта пользователя поля, заданные по умолчанию. Если вам нужны дополнительные поля или в целях повышения производительности нужно сократить полезную нагрузку ответа, добавьте параметр fields и запросите требуемые поля:
В методе обратного вызова данные ответа десериализуются в JSONObject , если запрос выполнен успешно. Поля, которые невозможно извлечь из-за отсутствия необходимых разрешений, будут исключены из результата.
Для пользователя, который выполнил вход, в SDK есть классы Profile и ProfileTracker . См. раздел Вход через Facebook для Android.
Доступ к данным пользователя
Доступ к данным зависит от того, какие разрешения предоставлены приложению и какие данные доступны приложениям. Вот пример необработанного отклика API Graph для user_location и user_birthday :
Обработка результатов
В зависимости от эндпойнта вызова вы получите JSONObject или JSONArray .
При вызовах одиночного объекта, например newMeRequest , возвращается JSONObject . Вызовы для получения списка результатов, например newMyFriendsRequest , возвращают JSONArray .
Обработка ошибок
Вы можете изучить поле ошибок в объекте GraphResponse , чтобы понять, удалось ли выполнить запрос. Поле ошибок относится к типу FacebookRequestError . Вы можете вызвать следующие методы:
В объекте ошибки есть поля, в которых приведена подробная информация об ошибке, в том числе:
Подробнее о возможных кодах ошибки см. в разделе Использование API Graph, Обработка ошибок.
Объект GraphResponse также содержит элемент enum , который присваивает категорию ошибкам. Есть три категории ошибок:
Устранение неполадок
Если проблема связана с извлечением данных пользователя, активируйте регистрацию HTTP-запросов. Для этого нужно добавить код перед разделом, в котором приложение запрашивает данные пользователя:
Это позволит зарегистрировать информацию о запросах и ответах HTTP в журнале консоли.
Пакетные запросы
Вы можете использовать пакетные запросы данных, если приложение обрабатывает следующие типы сценариев:
Пакетные запросы позволяют сократить число циклов запроса и ответа для сервера. Например, мы хотим извлечь данные о пользователе и его друзьях:
Источник
Integrating the Facebook Graph API in Android
In this tutorial, I will show how to send requests and get data from Facebook using the Graph API.
You can find the project on Github
In order to perform requests to the Graph API, the user must be logged in with the Facebook SDK for Android.
You can find the Facebook Login Integration article here
Create Project and Set up SDK
Make sure you have an up to date version of Android Studio. I am using version 2.2.3
Open Android Studio and create a New Project, naming it as you wish. Click Next, choose Minimum API level 17 and click Next again. Choose Empty Activity as the first activity, name it LoginActivity and click Finish.
Next, we add another blank activity to the project. Right Click the package and select New -> Activity -> Blank Activity. Leave its name as default and click Finish.
Open build.gradle (Project) and add mavenCentral() to both repository sections. Then open build.gradle (Module) and add the SDK library by adding this line to dependencies:
Open strings.xml and add this line
Make sure you have given the Internet permission to your app by adding:
in your AndroidManifest.xml file.
In the same file, inside the tags, add:
Logging in
Add the Facebook Login Button inside the activity_login.xml layout:
This is the only widget shown in the LoginActivity.
Open the LoginActivity class. First we need to initialize the Facebook SDK by adding :
before the setContentView() line.
Initialize these variables before onCreate() method:
After the setContentView() method, add these lines:
Here we create a callbackManager which will be registered to our Facebook Login Button.
An instance of the Login Button will be created by adding:
Now it’s time to create the Login Result Callback . This callback will be attached to the login button together with the callbackManager we created before.
The Login Result Callback’s code is as below:
This callback has three Overriden methods: onSuccess() , onCancel() and onError . Each time the user logs in, only one of the methods will be called.
Inside the onSuccess() method, a new GraphRequest will be created. This request will take two arguments: the login result access token (loginResult.getAccessToken()) and a new GraphRequest with a JSONObjectCallback .
If the request is successful, a new Activity will be started
The GraphRequest response would be of type JSONObject and it will contain the required fields.
Before the onCreate() method closing tag, we need to add the loginButton read permissions .
The last method of the LoginActivity class is:
Getting and Sharing data to Facebook
After the user has logged in, a new Intent will be started. The next activity is MainActivity class.
Be sure that your public class MainActivty implements View.OnClickListener .
Its layout’s xml code is:
Open the MainActivity class and before the `onCreate()’ add these lines:
The first thing to do after the activity is created, is taking the intent extras put from the previous activity.
We can use the name and surname variables to display the user information by using:
Since our MainActivity class is implementing a View.OnClickListener we need to @Override the onClick(View view) method:
This is the share() method:
The method above shares a link content. You can use the similar methods like SharePhotoContent , ShareVideoContent , ShareFeedContent , ShareMediaContent etc. The content should always be shown inside the ShareDialog .
In order to get the user timeline posts, we need to make a GraphRequest :
In this case, user posts are the only data we can get from the profile, because this is the only permission request on login:
You can see the permissions below:
or you can try the Graph API Explorer for a better understanding how it works.
The logout() method is:
Conclusion
The Facebook Graph API is much more wider than that. This was just a simple use of that, purposing to show how it is implemented in Android.
If you have any questions please let me know by comments below.
Источник
Graph API Reference
Graph API Root Nodes
Get Fields and Edges on an Album.
Represents an async job request to Graph API
An Atlas Campaign
Conversion Event Node
An Atlas Publisher
An Atlas Report
An Atlas ReportRun
An Atlas ReportSchedule
An Ad Platform Tracking Connection
Represents a group of certain types of Business objects in a Business. Will be used by Measurement Hub initially with more usage coming later on.
Returns a recommendation of a single retailer for a specific brand. This endpoint returns a retailer-brand pair and an advertiser who can advertise on behalf of the producer.
This endpoint is mainly for Facebook’s Marketing Partners using Collaborative Ads.
A collaboration request is a partnership request coming from a brand or agency to a retailer or marketing partner. Used for Collaborative Ads.
A domain name that has been issued new certificates.
A canvas document
A button inside the canvas
A carousel inside a canvas
A footer of the canvas
A header inside the canvas.
A photo inside a canvas
A product list inside the canvas
A product set inside the canvas
A store locator inside the canvas
Text element of the canvas
A video inside canvas
Directory of retailers that use Collaborative Ads. This endpoint must be used in conjunction with the collaborative_ads_merchants field below.
Commerce Merchant Settings object
Represents an order placed directly on Facebook or Instagram
Represents a destination in a catalog
Get fields and edges on an Event.
Represents a flight in a catalog
Represents a copyright on an image asset.
Get fields and edges on a LiveEncoder.
Get fields and edges on a LiveVideo.
An ingest stream for a live video
A mailing address object
Graph API Reference Milestone /milestone
A native offer represents an Offer on Facebook. The /
First revision to publish
A Data Set for Offline Conversions object
A subset of Offline Event Data Set
Get groups a Page is a member of.
A Facebook feed story
Notification of page upcoming changes.
This object represents a single Insights metric that is tied to another particular Graph API object (Page, App, Post, etc.).
This represents a Photo on Facebook.
The category of a place Page
A Facebook Feed story
A dynamically generated Post, used for Dynamic Ad Creatives
Graph API Reference Request /request
Represents settings specific to local inventory of a product catalog
Get fields and edges on a User.
A video copyright
A video copyright rules
A playlist for videos
Embedded video poll
Represents a single poll option that may be selected by the user
Returns the account information of a WhatsApp Business Account
Returns information about a specific phone number.
Retrieves information about the message template
Graph API Reference Thread /thread
A Facebook group.
Graph API Reference Group Doc /group-doc
This reference describes the /comments edge that is common to multiple Graph API nodes. The structure and operations are the same for each node.
A comment can be made on various types of content on Facebook. Most Graph API nodes have a /comments edge that lists all the comments on that object. The /comment node returns a single comment.
Private replies for an object
This reference describes the /likes edge that is common to multiple Graph API nodes. The structure and operations are the same for each node.
Graph API Reference Conversation /conversation
Graph API Reference Payment /payment
Graph API Reference Profile /profile
Graph API Reference /object/sharedposts
An individual message in the Facebook messaging system.
A link shared on a wall.
Graph API Reference Test User /test-user
Graph API Root Edges
Returns archived ads based on your search. By default we only return all ads that are eligible for delivery and that have the ACTIVE status.
Источник
Facebook SDK for Android
This documentation describes how to integrate your Android app with Facebook to build engaging social apps by using the Facebook SDK for Android. To learn more about using Facebook development tools, see App Development.
The current version of the Facebook SDK for Android is version 12.0.0 and requires the Android API 15. Code and samples for the Facebook SDK for Android are available on GitHub.
Beginning with SDK v13.0, set to release in early 2022, a Client Token will be required for all calls to the Graph API.
When you use the Facebook SDK for Android, follow the Facebook Open Source Terms of Use and Privacy Policy.
Common Uses
The Facebook SDK for Android gives you access to the following features:
Facebook Login — A secure and convenient way for people to log into your app or website by using their Facebook credentials.
Sharing — Enable people to post to Facebook from your app. People can share, send a message, and share to stories.
App Events — Understand people’s actions in your app and measure the effectiveness of your Mobile App Ads.
Graph API — Get data in and out of Facebook’s social graph, query data, post stories, upload photos and perform other tasks.
Advertise Your App — Drive installs of your app by using Mobile App Install Ads. Increase engagement with your app by using Mobile App Engagement Ads. Find your target audience with Custom Audiences for Mobile Apps.
Documentation Contents
Component SDKs
Describes the component SDKs of the Facebook SDK for Android.
Getting Started
A short tutorial to get you up and running.
Calling the Graph API from Android
Learn how to call the Facebook Graph API from your Android app.
FAQ & Troubleshooting
Frequently asked questions and troubleshooting information for the Facebook SDK for Android.
Changelog
Changelog and release notes for the Facebook SDK for Android.
Upgrade Guide
Instructions for upgrading your version of the Facebook SDK for Android.
Devices
Considerations when you use the Facebook SDK for Android with Android TV and Amazon’s Fire TV.
Reference
Component and endpoint references.
Downloads
Instructions to reference the Facebook SDK for Android in your app and links to download old versions.
Deprecated
Resources for old versions of the Facebook SDK for Android.
Источник