Android facebook user friends

Getting started with the Facebook for Android SDK

Many mobile apps allow the user to post content to popular social media platforms, such as Facebook, Twitter and LinkedIn.

This kind of social sharing can be a great way to promote your app, and can improve the user experience by creating a connection between your application and the user’s favorite social media networks.

To promote social sharing, many of the major social platforms have created tools that specifically target app developers – and Facebook is no exception!

In this article, I’ll show you how to add Facebook integration to your Android applications, using the Facebook for Android SDK (Software Development Kit). Once you’re connected to the official Facebook SDK, you’ll have access to a wide range of features, but in this article we’ll be focusing on two of the most popular: authenticating with Facebook, and social sharing.

By the end of this article, you’ll have created an application that allows users to authenticate their identify using their Facebook credentials, and then share your app’s content, by posting it to Facebook.

What is the Facebook for Android SDK?

Every social media platform wants to drive user engagement, and enabling users to share content from a range of sources is a powerful way to keep them engaged with your platform.

The official Facebook SDK for Android helps you create apps that integrate with Facebook, and provides access to several key features, including Facebook authentication, and reading and writing to the platform’s APIs.

The Facebook SDK for Android compromises of the following components:

  • Analytics. Provides access to aggregated and anonymized data, so you can analyze how people are using your app.
  • Login. Allows people to sign into your app using their Facebook credentials. If the user is already signed into the Facebook for Android mobile app, then they won’t have to re-enter their username and password, in order to authenticate with your application. Once a user is signed in with Facebook, you can retrieve information and perform actions on their behalf, such as displaying their Facebook profile pic inside your app, or posting status updates.
  • Account Kit. Makes it possible for users to authenticate their identify, using just their phone number or email address. Account Kit doesn’t require a Facebook account, which makes this a viable authentication method for any users who haven’t signed up to Facebook.
  • Ads. If you want to monetize your application, then you can use this component to create and run ad campaigns.
  • App events. Allows you to track a range of user actions and events within your app. You can use this information to evaluate the effectiveness of your Mobile App Ads, or to identify the users who are most likely to respond to your adverts.
  • App Links. Imagine a user has just posted some of your app’s content to Facebook; App Links let you specify what happens, when someone interacts with this content. For example, they might get forwarded to your app’s Google Play listing, or your company’s website. Alternatively, if someone already has your app installed on their device, then you may respond by launching your application, and taking them to an Activity related to this content.
  • Graph API. By integrating with the Facebook Graph API, you can retrieve data from the Facebook platform, and add data such as posting new stories and uploading photos.

What are the benefits of Facebook integration?

For developers, the Facebook for Android SDK has several benefits.

1. Seamless sign up

Depending on your application, users may need to authenticate their identity before they can access certain features. Even if your application only requires an email address and password, there’s always going to be a percentage of mobile users who decide this is too much hassle, and exit your application.

Читайте также:  Last fortress для андроид

There’s several reasons why we’re much less likely to complete a registration form on a mobile device, compared to our laptop or computer. Firstly, we tend to use smartphones and tablets on the go, and often under time constraints, for example you might spend a few minutes playing on your phone while you’re waiting at the doctor’s office, in line at the supermarket, or at your local bus stop. None of these scenarios are ideal for completing an in-app form!

In addition, typing on your mobile device’s small, virtual keyboard can be time-consuming and frustrating, particularly for users who have manual dexterity issues, or anyone who’s prone to typos. Typing a password that contains a mixture of symbols, numbers, and upper and lowercase letters, can feel like a huge effort on your smartphone or tablet.

By adding Facebook login to your application, you can replace an in-app registration form, with single-tap authentication.

Источник

Публикация контента в Android

В этом руководстве поясняется, как интегрировать в приложение Android функцию публикации контента на Facebook. Контент, которым люди делятся через ваше приложение, появляется в их хронике, а также может отображаться в Ленте новостей их друзей.

Кроме того, контентом из приложения можно делиться в Facebook Messenger.

Предварительные требования

Прежде чем дать пользователям возможность делиться на Facebook контентом из приложения, нужно привязать или скачать Facebook Sharing SDK для Android.

Sharing SDK для Android — это компонент Facebook SDK для Android. Чтобы использовать Facebook Sharing SDK в проекте, сделайте его зависимостью в Maven.

Привязывание Facebook SDK с использованием Maven

Откройте в своем проекте your_app | Gradle Scripts | build.gradle (Project) и добавьте в раздел buildscript < repositories <>> следующий репозиторий:

Откройте в своем проекте your_app | Gradle Scripts | build.gradle (Module: app) и добавьте в раздел dependencies<> следующее выражение:

При использовании Facebook SDK некоторые события в приложении регистрируются и собираются автоматически (если не отключить их автоматическую регистрацию). Подробнее о том, какая информация собирается и как отключить автоматическую регистрацию событий, см. в разделе, посвященном автоматической регистрации событий в приложении.

Дальнейшие предварительные требования

Выполните следующие действия:

Подробные сведения об этих требованиях см. в статье Начало работы с SDK для Android.

Также потребуется настроить ContentProvider в файле AndroidManifest.xml , где — ID вашего приложения:

Приложение, в котором интегрирована публикация контента, не должно заранее заполнять поля для контента, которым люди хотят поделиться. Это нарушение Политики платформы Facebook (см. правила для разработчиков).

Моделирование контента

В Facebook SDK версий 4.0 и выше предусмотрены новые модели публикации контента. Для каждого типа контента, которым хотят поделиться люди, предусмотрен свой класс. После моделирования контента добавьте в приложение интерфейс публикации.

Ссылки

Когда люди публикуют на Facebook ссылки из вашего приложения, в публикацию добавляется contentURL с соответствующей ссылкой. Подготовьте ссылки для публикации, используя модель ShareLinkContent . Список всех атрибутов см. в справке по ShareLinkContent .

Пример кода для запуска публикации:

Чтобы предварительно просмотреть публикуемую ссылку на App Store или Google Play, введите ее URL в отладчике репостов.

Если ваша публикация содержит ссылку на приложение в Google Play или App Store, описание и изображение в публикации будут игнорироваться. Вместо этого мы загрузим название и изображение приложения из магазина (если изображения в магазине нет, его не будет и в публикации).

Люди могут делиться на Facebook фотографиями из вашего приложения. Для этого используется диалог «Поделиться». Кроме того, на устройстве должно быть установлено нативное приложение Facebook для Android (версии 7.0 или более поздней).

Подготовьте контент фото для публикации, используя модель SharePhotoContent . Список всех атрибутов см. в справке по SharePhotoContent .

Видео

Люди могут делиться на Facebook видео из вашего приложения. Для этого используется диалог «Поделиться».

Подготовьте контент видео для публикации, используя модель ShareVideoContent . Список всех атрибутов см. в справке по ShareVideoContent .

Мультимедийный контент

Люди могут делиться мультимедийным контентом, содержащим фото и видео, из вашего приложения на Facebook с помощью диалога «Поделиться». Обратите внимание на следующие ограничения:

Читайте также:  Teamviewer quicksupport android apk

Подготовьте мультимедийный контент для публикации, используя модель ShareMediaContent . Список всех атрибутов см. в справке по ShareMediaContent .

Добавление интерфейсов для публикации контента

После создания модели контента запустите интерфейс Facebook для публикации.

Кнопки

Для запуска публикации контента можно воспользоваться нативными кнопками Facebook для Android.

Кнопка «Поделиться»

Кнопка «Поделиться» служит для вызова диалога «Поделиться». Чтобы добавить кнопку «Поделиться», вставьте в представление следующий фрагмент кода:

Диалог «Поделиться»

Этот диалог служит для переключения в нативное приложение Facebook для Android. После публикации он возвращает управление вашему приложению. В зависимости от используемого вами SDK для возврата в приложение, возможно, потребуется нажать стрелку назад. Если на устройстве не установлено приложение Facebook, диалог «Поделиться» автоматически переключается на веб-диалог.

Например, чтобы показать диалог ShareDialog для ссылки в вашем действии, создайте в методе onCreate экземпляр ShareDialog :

Затем покажите диалог ShareDialog:

Наконец, в onActivityResult вызовите callbackManager из SDK для обработки ответа:

Если вы используете действия или фрагменты AndroidX, не нужно переопределять onActivityResult .

Диалог сообщения

Этот диалог служит для переключения в нативное приложение Messenger для Android. После публикации он возвращает управление вашему приложению. В зависимости от используемого вами SDK для возврата в приложение, возможно, потребуется нажать стрелку назад.

Дополнительные функции

При использовании диалога «Поделиться» Facebook вы можете применять дополнительные функции, которые недоступны, если вы публикуете контент с помощью API.

Хэштеги

Для фото, ссылки или видео, которыми вы делитесь, можно указать один хэштег. Он также будет отображаться в диалоге «Поделиться». При желании люди могут удалить его перед публикацией.

Ниже показано, как добавить хэштег к ссылке.

Публикация цитаты

Вы можете позволить людям самостоятельно выделять текст, который будет отображаться как цитата со ссылкой. Кроме того, вы можете сами выбрать цитату, например врез в статье, который будет отображаться вместе со ссылкой. В любом случае цитата отображается в собственном поле отдельно от комментариев пользователя.

Дополнительные материалы

Встроенные альтернативные диалоги для публикации контента

В предыдущих версиях Facebook SDK для Android, прежде чем открыть диалог «Поделиться», приложению необходимо было проверить, установлено ли на устройстве нативное приложение Facebook, и предусмотреть соответствующий код для вызова альтернативной версии диалога, если оно отсутствует.

Теперь SDK автоматически проверяет наличие на устройстве нативного приложения Facebook. Если оно отсутствует, SDK переключает пользователя в его браузер по умолчанию и открывает диалоговое окно.

С помощью App Links можно создавать обратные ссылки на ваше приложение из публикаций на Facebook, которыми поделились из него. Когда человек нажимает такую публикацию, открывается ваше приложение. Можно также создать ссылку на определенный контент в приложении.

Источник

Android facebook user friends

Friend Smash sample Facebook game

  • Peter Chang (peter78)
  • Phil Hewinson (philhewinson)
  • Ali Parr (aliparr)
  • Jakub Pudelek (skoggkatt)

To help better understand different products and services available to game developers, Facebook maintains a sample game called Friend Smash!

The game is implemented on different platforms:

  • Web using Facebook SDK for Javascript
  • Mobile using Facebook’s native SDKs for iOS and Android
  • It is also available as a Unity cross platform build using the Facebook SDK for Unity.

There are minor differences between the four implementations, but overall the goal and structure of all is similar. This is the Android version of the game.

What is “Friend Smash!”?

Friend Smash is a simple game which utilizes Facebook platform to enhance the gameplay by making it more fun and social. It uses variety of products and services, such as Facebook Login, Graph API, Game Requests and Sharing. The code examples serve as a guide of how they may be used in a games context. It also serves as an implementation guide — parts of source code relevant to Facebook integration are clearly separated from the pure gaming-logic and clearly documented with in code comments.

Please note that Friend Smash! was not designed as an example of how to design or code a game. The focus is on Facebook integration — other parts of the project may not be as clear and well designed and documented.

Friends Smash! is a game in which players are tasked with «smashing» (mouse-clicking or screen-tapping) pictures of a specific person while avoiding smashing pictures of anyone else. Player gets points for each correct picture smashed. Each miss or wrong smash causes the player to lose a heart. After losing 3 lives, the game is over. Player can also smash images of coins to collect them and later redeem these coins to buy bombs. In turn, bombs can be used in game to smash all correct pictures on the screen, helping to achieve a higher score. Additionally, the web version of the game allows players to purchase coins with Facebook Payments.

Читайте также:  Лучшие андроид телефоны до 8000

To make the experience more fun and social, players are asked to log in with Facebook and grant user_friends permission. When granted, the game will have access to subset of player’s friends data, specifically those who also logged in to Friend Smash! and granted user_friends permission. This means the game will use the profile picture of randomly selected friend as the picture the player is asked to smash. If user_friends permission hasn’t been granted or the player doesn’t have friends who also logged in to Friend Smash! and granted user_friends permission, a picture of randomly selected celebrity is used instead.

At different points in the game player has an opportunity to share to Facebook. For example after the game is over, player can brag about the score achieved by posting a custom Open Graph story. The game also shows how to ask for publish_actions permission (which is required for API based sharing) and how to handle the case when publish_actions permission is not granted. If publish_actions permission is granted — the game uses Scores API to publish and store the top score achieved by the player.

Game Requests are used in the game for two main purposes. First to let the player invite their friends who are not playing the game to try it. Second, to send a challenge to a friend who is already playing to bring them back to the game. Additionally on the web version, the game uses Facebook Payments to allow players to purchase in-game currency and In-Game Gifting to allow purchasing gifts for players’ friends. The web example also includes reference implementation of a payments server handling static pricing and payments verification.

Friend Smash! also logs App Events, which enables Facebook Analytics for Apps — a free tool allowing developers to learn how people use their app across all platforms and devices, get insights about the people using the app, and improve marketing.

How to use “Friend Smash!”?

All versions of Friend Smash! are available as part of Facebook Platform Samples on github: Web, Android, iOS, Unity.

The recommended way to explore the projects is to begin with how Facebook products are integrated. To make it easier code responsible for Facebook integration is separated and well documented with in code comments for all versions. You can find it here for different versions: Web, Android, iOS, Unity. The reference implementation of a payments server is included in the Web repository.

To play Friend Smash! on Web, simply go to apps.facebook.com/friendsmashsample. To play it on mobile, download the Android, iOS or Unity project and build it from source and try on your device.

Please note it is likely that unless you have friends who also installed Friend Smash! you will not see any of your friends in the game. If this is the case, you can invite some of your friends to play Friend Smash! to fully explore how social integration works in Friend Smash!

Before running the sample, please see the Getting Started on Android guide

Facebook SDK for Android documentation

All contributors must agree to and sign the Facebook CLA prior to submitting Pull Requests. We cannot accept Pull Requests until this document is signed and submitted.

About

Built natively in Eclipse, using Java, Friend Smash for Android integrates the Facebook SDK for Android to provide easy login, increased engagement and improved organic distribution. Learn how to build Facebook into an Android app from the ground up.

Источник

Оцените статью