Android studio social network

Простой и удобный способ добавления социальных сетей в Андроид приложение на примере Вконтакте и Одноклассники

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

Для этого можно воспользоваться модулями библиотеки ASNE.

Используя модуль библиотеки вы подключите SDK или API выбранной социальной сети и интерфейс для наиболее часто используемых запросов к ней, тем самым сэкономив время и упростив добавление другой социальной сети. Благодаря использованию SDK, пользователь может залогиниться или расшарить запись через уже установленное приложение социальной сети. А добавить социальную сеть как модуль, если ее нет в разработанных, не составит труда — это легко сделать по аналогии с любым другим модулем.

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

Регистрация приложения в социальной сети

Для добавления социальной сети в приложение потребуется ключ для совершения запросов. Поэтому первым шагом необходимо зарегистрировать приложение — по ссылкам вы увидите краткое руководство по созданию приложения для:

  • VK
  • Odnoklassniki

Для продолжения работы потребуются следующие ключи, которые используются в SDK социальных сетей.

  • VK App ID
  • OK App ID
  • OK Public Key
  • OK Secret Key

Интеграция Вконтакте и Одноклассники в приложение

После создания нового проекта сохраним ключи в values/strings.xml:

Затем добавим uses-permission для работы с интернетом и activity, необходимую «Одноклассниками» для взаимодействия с приложением в манифест.

Теперь добавим зависимости для модулей ASNE, например, в Android Studio для этого необходимо:

Открыть Project Structure => выбрать модуль приложения и открыть Dependencies => Add new library dependency

Затем по запросу asne вы увидите все модули доступные в библиотеке и добавьте в зависимость asne-vk, asne-odnoklassniki:

Либо вручную добавьте зависимости в build.gradle.

Немного украсим наше приложение:
В главном фрагменте расположим 2 кнопки, отвечающие за логин в социальные сети.

Для обработки ответа после запроса логина переопределим в MainActivity.java метод onActivityResult.

При обработке запроса логина социальная сеть отправляет onActivityResult проверяем его и отправляем в SocialNetworkManager, который передаст его в соответствующую SocialNetwork.

Теперь интегрируем социальную сеть в MainFragment.java — это просто:

    Возьмем ключи социальных сетей из values.xml

Создадим SocialNetworks с соответствующими разрешениями:

Проверим существует ли SocialNetworkManager

    Если не существует зададим его и добавим в него SocialNetworks

Если SocialNetworkManager существует(задали в activity или другом фрагменте) — выберем все инициализированные социальные сети и установим им OnLoginCompleteListener

Теперь необходимо обработать ответ после инициации SocialNetworks

Весь исходный код onCreateView и onSocialNetworkManagerInitialized из MainFragment c инициацией социальных сетей.

Запросы к Социальным сетям

Для начала запросим логин в социальной сети, для этого потребуется лишь id

Код OnClickListener loginClick с проверкой состояния подключения к социальной сети, а если пользователь уже вошел через социальную сеть — откроем ProfileFragment.java

После обработки логина приложением социальной сети получим onLoginSuccess(int networkId) или onError(int networkId, String requestID, String errorMessage, Object data) — выведем соответствующее сообщение.

Откроем ProfileFragment.java с помощью метода:

В ProfileFragment.java получим идентификатор социальной сети из MainFragment.java

Теперь с помощью networkId мы выберем социальную сеть и запросим данные профиля текущего пользователя следующим образом:

Читайте также:  Какие андроид телефоны выйдут

не забудьте добавить OnRequestSocialPersonCompleteListener
После обработки запроса мы можем использовать полученный объект SocialPerson для заполнения профиля пользователя в приложении, либо вывести ошибку при неудаче

Для выхода из социальной сети необходимо использовать метод logout()

И, честно говоря, это все — добавили ВК и Одноклассники в приложение. Как оказалось это достаточно просто и быстро. Аналогично можно добавить и другие социальные сети Facebook, Twitter, Linkedin, Instagram или Google Plus лишь добавив соответствующую зависимость и добавив их в SocialNetworkManager

Конечно же вы можете использовать выше описанные методы для работы с ними

Но давайте разберем еще несколько запросов — поделиться ссылкой и вывод списка друзей
Давайте поделимся ссылкой с помощью социальной сети:
Для начала настроим кнопку

Для отправки ссылки на стену пользователя нам необходимо ее передать в Bundle

И конечно же обработать ответы

Итак в OnClickListener shareClick покажем пользователю простой диалог в котором спросим, хочет ли он поделиться ссылкой, и если да, отправим ее

И на стене пользователя успешно появилась ссылка с предпросмотром и описанием

Теперь выведем список друзей пользователя:
Получим SocialNetwork из идентификатора социальной сети и запросим список друзей

Используя модули библиотеки ASNE можно легко и быстро добавить любую популярную социальную сеть в приложение. Конечно же в библиотеке содержится больше методов которые возможно пригодятся в вашем приложении. А так же можно использовать любые методы SDK или API используя токен или объект SDK

Если данное приложение вам показалось простым, вы можете посмотреть реализацию всех методов библиотеки в демо для библиотеки

Так же вы можете изучить аналогичную статью по подключению Facebook, Twitter and LinkedIn на codeproject.com.

В данный момент библиотека стабильна и находится в состоянии добавления социальных сетей. Буду рад вашим советам или помощи в разработке.

В планах развития библиотеки:

  • Описание добавления своего модуля — в вики репозитория(на самом деле все очень просто);
  • Добавление китайских социальных сетей;
  • Написания javdocа и тестов.

Источник

How to Create a Social Media App on Android Studio?

Social media is not a new term for us. Our daily life is incomplete, or we can say we human beings survive on food, water, air, and social media. We are dependent to such an extent that we tend to share every bit of information about ourselves on social media platforms. Similarly, Android Studio is also not a new term for an Android Developer. For beginners there always a curiosity about how a complex app like Facebook, Instagram, Twitter, Linked In, etc. is developed. How do these apps work!! How do the likes, comments functionalities work in social media apps!! How does the messaging functionality works!! And many more.

In the previous article “Best Way to Become Android Developer – A Complete Roadmap” we have discussed that “The best way to learn Android is by developing some basic projects to some advanced projects“. So in this article, we are going to develop something like that. We are going to develop a clone of a social media app.

List of Functionalities

  1. SignUp themselves using their email and password.
  2. SignIn themselves using their email and password that they have using during the Signup process.
  3. Edit their profile data (Profile Pic, Name, and Password).
  4. Add various blogs.
  5. Search for a specific blog.
  6. Show all registered users.
  7. Search for a user out of all registered users.
  8. Like a blog post.
  9. Comment on a particular blog.
  10. Show all users who liked a particular blog.
  11. Delete a Blog Post
  12. Send Message
  13. Delete Sent Message
  14. LogOut themselves and LogIn with their other ID.
Читайте также:  Google map android иконки

Use Case Diagram

Use Case diagram is a part of UML (Unified Modeling Language) that is used to depict the functionality of a system or a part of a system. They are widely used to illustrate the functional requirements of the system and its interaction with external agents (actors). A use case is basically a diagram representing different scenarios where the system can be used. A use case diagram gives us a high-level view of what the system or a part of the system does without going into implementation details. Below is the use case diagram for this project:

Implementation

Technology Stack Used:

  • For frontend:XML
  • For backend:Java
  • IDE:Android Studio
  • Database Used:Firebase

A sample video is given below to get an idea about what we are going to do in this tutorial.

This tutorial has comprised of 16 parts as the following:

Part 2:Create Fragment Using Bottom Navigation

  • We are going to Create Bottom Navigation with 5Fragments (Home, Users, AddBlog, ChatList, Profile).
  • On HomeFragment we will be Showing all the added blogs.
  • In the UsersFragment, we will be showing all the Registered Users.
  • In the AddBlogFragment We will be adding our blogs.
  • In the ChatlistFragment we will be showing a chat list of all users with whom we have chat.
  • In the ProfileFragment We will be showing the Profile of the user where we will be showing users’ data and the blogs written by the user.

Part 3:Edit Profile Data

  • We are going to edit our profile data like changing name, changing the password of the user, and changing profile pic.
  • Changing password is a very important feature because it may happen that sometimes someone knows our password and in that case, we need to change our password.
  • We change our profile pic using selecting an image from the gallery or clicking an image from the camera.

Part 5:Add Blogs

  • We are going to add blogs by any user. Here we are going to work in AddBlogs Fragment where the user will be adding a blog with a title, description, and an image related to that blogs.
  • If the user doesn’t write any of the titles or descriptions then we will be showing an error.

Part 6:Retrieve Blog On Home Page

  • We are going to retrieve the blogs written by users on HomeFragment.
  • Here we have only shown the user data and title, description, and image of the blogs, but we are also going to implement the like and comment feature in upcoming blogs.
  • Then We will be showing Post details Activity where users will be able to comment.
  • We have also implemented the Like a Blog functionality.

Part 7:Search for a Specific Blog On Home Page and Logout Functionality

  • We are going to Search For a Blog on Home Page.
  • If there are few blogs in our app then it is easy to search for a blog manually. But what happens when we have 1000 blogs then search for a particular blog became a very complicated and time taking task.
  • That’s why we are implementing this feature to search for a blog using the title or description provided.
  • Also, we have implemented the Logout functionality in this article.

Part 8:Show All Registered Users

  • We are going to Show all the Registered Users of our App.
  • We are going to show the list of users in UsersFragment.

Part 9:Search For a User Out of All Registered Users

  • We are going to Search For a user on the Users Page.
  • If there are few people registered in our app then it is easy to search for a person.
  • But what happens when we have 1000 users registered in our app then searching for a particular user became a very complicated and time taking task.
  • That’s why we are implementing this feature to search for a user using the name or email provided.
Читайте также:  Plants vs zombies взлом android

Part 10:Like a Blog Post

  • We are going to Like a Blog. We are implementing this feature using two images one like button with white background and another like button with blue background.
  • When the user clicks on the button for the first time we will change the image to the button with the background color blue and will increase the count. When the user clicks again then we will decrease the count and change the like button with background white.

Part 11:Comment on a Particular Blog

  • We are going to comment on the blog.
  • Here we are going to write a comment, and then we will be showing the comments and will be updating the comment count.
  • The comment feature is the best feature in any blogging app. It helps in interacting with the user who has written the blog and much more.

Part 12:Show All Users Who Liked On a Particular Blog

  • We are going to view the list of users who have like a particular blog.
  • After Click on total like we will be redirected to PostLikedBy.Activity.
  • In that, we will be using a recycler view to show the list of users who have liked a post.
  • We can also view the list of all users who likes our post from the PostDetailActivity.class.

Part 13:Delete a Blog Post

  • We are going to delete the Blog written by the user.
  • Blogs can only be deleted by the owner of blogs. In the top right of the blog, a button is there.
  • After clicking on that a popup will come in that Delete button will come. After clicking on Delete, the blog will be successfully deleted from the blogs.

Part 14:Create Layout & Send Message in Chat

  • We are going to Create a Layout for chat & Send Messages in Chat.
  • A user can send either a Message or an Image.
  • A user can send an image either using a camera or gallery.
  • Firstly a request for permission will be asked to send an image using a gallery or after clicking the image using the camera.
  • If permission is given then the user can send the image or it will again request for asking permission.

Part 15:Delete Messages

  • We are going to delete the message in the ChatActivity.
  • We are going to delete text and image messages. When we click on a text then an AlertBox will come.
  • There will be two options to either delete that message or cancel the event. After Click on delete message will be deleted from both sides.

Part 16:Retrieve Blogs on User Profile

  • We are going to Retrieve Blogs Written by users on their profile fragment.
  • As previously we have already added Data of users in Profile Fragment like email, name, and profile pic.
  • Here we are also going to retrieve Blogs Written By the current user on their profile.
  • Let’s See the implementation of showing the blogs written by the current user.

Источник

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