ASNETutorial Android Arsenal Codeproject

Simple example project for https://github.com/gorbin/ASNE library

Today social network integration to your android application is common practice - it makes user easily login to your app and share their actions. There are a lot of ways to do it - usually developers add native social network SDK or use API for every network. It provides login via installed social network application or native dialogs. You have to spend time and nerves to learn and use different social network SDKs.

What if you need to add one more social network for your application? Sometimes you have to reorganize or redo all your integrations. This leads to idea to create and implement common interface for all social networks. Fortunately there is an open source modular library ASNE that allows you to choose necessary social network and provides full sdk and common interface for most oftenly used requests(login, share, friendslist & etc) It saves your time and simplifies adding another networks in the future. Moreover you can easily add any other social network as new module - the similar way as it's done in other modules.

In this tutorial you can learn how easily integrate Facebook, Twitter in android application using ASNE modules. This is very basic tutorial with login, sharing link and showing friends list.

##Registering app - getting keys for your application In order to implement Social networks in your application you need keys to make API calls. So register a new social network application and get the keys. Check small tutorial how to get it:

To continue you need

  • Facebook App ID
  • Twitter consumer key and consumer secret
  • LinkedIn consumer key and consumer secret

##Integrating Facebook, Twitter and LinkedIn to your application

  1. Create new Project in Android Studio

  2. Let's save our social network keys in values/strings.xml

    strings.xml(full source)

    <?xml version="1.0" encoding="utf-8"?>
       <resources>
           <string name="app_name">ASNE-tutorial</string>
       
           <string name="facebook_app_id">
               1646388738920557
           </string>
           <string name="twitter_consumer_key">
               BBQAUAVKYzmYtvEcNhUEvGiKd
           </string>
            byZzHPxE1tkGmnPEj5zUyc7MG464Q1LgNRcwbBJV1Ap86575os
        </string>
           <string name="linkedin_consumer_key">
               75ubsp337ll7sf
           </string>
           <string name="linkedin_consumer_secret">
               8DVk4hi3wvEyzjbh
           </string>
       </resources>
  3. Add permissions and meta data - open AndroidManifest.xml file and add uses-permission for INTERNET, ACCESS_NETWORK_STATE and add meta-data for facebook(add appId key)

    AndroidManifest.xml(full source)

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="asne_tutorial.githubgorbin.com.asne_tutorial" >
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <meta-data
                android:name="com.facebook.sdk.ApplicationId"
                android:value="@string/facebook_app_id"/>
        </application>
    
    </manifest>
  4. Set dependencies for asne-modules:

    Open Project Structure => choose your module and open Dependencies => Add new library dependency

add library dependecy

Then search for asne and add asne-facebook, asne-twitter, asne-linkedin

search asne

or just add them manually to build.gradle

build.gradle(full source)

apply plugin: 'com.android.application'

    android {
       compileSdkVersion 19
       buildToolsVersion '20.0.0'
       
       defaultConfig {
           applicationId "asne_tutorial.githubgorbin.com.asne_tutorial"
           minSdkVersion 10
           targetSdkVersion 19
           versionCode 1
           versionName "1.0"
       }
       buildTypes {
           release {
               runProguard false
               proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
           }
       }
    }
   
   dependencies {
       compile fileTree(include: ['*.jar'], dir: 'libs')
       compile 'com.android.support:appcompat-v7:20.0.0'
       compile 'com.github.asne:asne-facebook:0.3.1'
       compile 'com.github.asne:asne-linkedin:0.3.1'
       compile 'com.github.asne:asne-twitter:0.3.1'
   }
  1. Lets create some layouts Just login buttons in main fragment main_fragment.xml(full source)
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFCCCCCC">
    
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Login via Facebook"
            android:id="@+id/facebook"
            android:layout_gravity="center_horizontal"
            android:background="#3b5998"
            android:layout_margin="8dp"
            android:textColor="#ffffffff" />
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Login via Twitter"
            android:id="@+id/twitter"
            android:layout_gravity="center_horizontal"
            android:background="#55ACEE"
            android:layout_margin="8dp"
            android:textColor="#ffffffff"/>
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Login via LinkedIn"
            android:id="@+id/linkedin"
            android:layout_gravity="center_horizontal"
            android:background="#287bbc"
            android:layout_margin="8dp"
            android:textColor="#ffffffff"/>
    </LinearLayout>

Create simple profile card for user profile_fragment.xml(full source) ```xml

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_margin="8dp"
        android:id="@+id/frame"
        android:background="@color/dark">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_margin="3dp"
            android:id="@+id/card"
            android:background="#FFFFFF">

            <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/imageView"
                android:layout_margin="8dp"
                android:padding="2dp"
                android:background="@color/grey_light"
                android:layout_alignParentTop="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:src="@drawable/user"
                android:adjustViewBounds="true"
                android:cropToPadding="true"
                android:scaleType="centerCrop"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="NoName"
                android:maxLines="3"
                android:singleLine="false"
                android:id="@+id/name"
                android:padding="8dp"
                android:layout_alignTop="@+id/imageView"
                android:layout_toRightOf="@+id/imageView"
                android:layout_toEndOf="@+id/imageView"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="null"
                android:maxLines="3"
                android:singleLine="false"
                android:id="@+id/id"
                android:padding="8dp"
                android:layout_below="@+id/name"
                android:layout_alignLeft="@+id/name"
                android:layout_alignStart="@+id/name" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:id="@+id/info"
                android:padding="8dp"
                android:layout_marginBottom="4dp"
                android:layout_below="@+id/imageView"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" />

        </RelativeLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/buttonLayout"
            android:layout_below="@+id/card"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:gravity="center"
            android:background="@color/grey_light">

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Friends"
                android:id="@+id/friends"
                android:padding="8dp"
                android:background="@color/dark"
                android:layout_marginRight="1dp"
                android:layout_weight="1"
                android:textColor="#ffffffff"/>
            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Share"
                android:id="@+id/share"
                android:padding="8dp"
                android:background="@color/dark"
                android:layout_weight="1"
                android:textColor="#ffffffff"/>
        </LinearLayout>
    </RelativeLayout>

</ScrollView>
```

and save social networks colors to

color.xml(full source) xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="grey_light">#FFCCCCCC</color> <color name="dark">#4b4b4b</color> <color name="facebook">#3b5998</color> <color name="twitter">#55ACEE</color> <color name="linkedin">#287bbc</color> </resources>

  1. Let's setup MainActivity.java We should set up onActivityResult method to catch responses after requesting login

    MainActivity.java(full source)

   public static final String SOCIAL_NETWORK_TAG = "SocialIntegrationMain.SOCIAL_NETWORK_TAG";
   
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
       Fragment fragment = getSupportFragmentManager().findFragmentByTag(SOCIAL_NETWORK_TAG);
       if (fragment != null) {
           fragment.onActivityResult(requestCode, resultCode, data);
       }
   }

After every login form social networks send onActivityResult and we should check it and send to our SocialNetworkManager which deliver it to right SocialNetwork

  1. Create MainFragment.java and begin transaction of this fragmetn in MainActivity.java

    MainActivity.java(full source)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new MainFragment())
                .commit();
        }
    
    }
  2. Integrating of any social network is simple:

    • Get SocialNetworkManager
    mSocialNetworkManager = (SocialNetworkManager) getFragmentManager().findFragmentByTag(MAinActivity.SOCIAL_NETWORK_TAG);
    • Get keys from values.xml - note Facebook appId we used in AndroidManifest.xml
    String TWITTER_CONSUMER_KEY = getActivity().getString(R.string.twitter_consumer_key);
    String TWITTER_CONSUMER_SECRET = getActivity().getString(R.string.twitter_consumer_secret);
    String TWITTER_CALLBACK_URL = "oauth://ASNE";
    String LINKEDIN_CONSUMER_KEY = getActivity().getString(R.string.linkedin_consumer_key);
    String LINKEDIN_CONSUMER_SECRET = getActivity().getString(R.string.linkedin_consumer_secret);
    String LINKEDIN_CALLBACK_URL = "https://asneTutorial";
    • Create chosen SocialNetworks with permissions
    ArrayList<String> fbScope = new ArrayList<String>();
    fbScope.addAll(Arrays.asList("public_profile, email, user_friends"));
    FacebookSocialNetwork fbNetwork = new FacebookSocialNetwork(this, fbScope);
    
    // permissions for twitter in developer twitter console
    TwitterSocialNetwork twNetwork = new TwitterSocialNetwork(this, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_CALLBACK_URL);
    
    String linkedInScope = "r_basicprofile+r_fullprofile+rw_nus+r_network+w_messages+r_emailaddress+r_contactinfo";
    LinkedInSocialNetwork liNetwork = new LinkedInSocialNetwork(this, LINKEDIN_CONSUMER_KEY, LINKEDIN_CONSUMER_SECRET, LINKEDIN_CALLBACK_URL, linkedInScope);
        
    • Check if SocialNetworkManager is null init it and add SocialNetworks to it
    mSocialNetworkManager = new SocialNetworkManager();
    
    mSocialNetworkManager.addSocialNetwork(fbNetwork);
    mSocialNetworkManager.addSocialNetwork(twNetwork);
    mSocialNetworkManager.addSocialNetwork(liNetwork);
    
    //Initiate every network from mSocialNetworkManager
    getFragmentManager().beginTransaction().add(mSocialNetworkManager, MAinActivity.SOCIAL_NETWORK_TAG).commit();
    mSocialNetworkManager.setOnInitializationCompleteListener(this);

    don't forget to implement SocialNetworkManager.OnInitializationCompleteListener

    • If SocialNetworkManager - come from another fragment where we already init it - get all initialized social networks and add to them necessary listeners
    if(!mSocialNetworkManager.getInitializedSocialNetworks().isEmpty()) {
        List<SocialNetwork> socialNetworks = mSocialNetworkManager.getInitializedSocialNetworks();
        for (SocialNetwork socialNetwork : socialNetworks) {
            socialNetwork.setOnLoginCompleteListener(this);
        }

    don't forget to implement OnLoginCompleteListener

    • Now we need to catch callback after initializing of SocialNetworks
    @Override
    public void onSocialNetworkManagerInitialized() {
        for (SocialNetwork socialNetwork : mSocialNetworkManager.getInitializedSocialNetworks()) {
            socialNetwork.setOnLoginCompleteListener(this);
            initSocialNetwork(socialNetwork);
        }
    }

    don't forget to implement OnLoginCompleteListener

Full onCreateView and onSocialNetworkManagerInitialized from MainFragment with initializing and setting listener to buttons

**MainFragment.java**(full [source](https://github.com/gorbin/ASNETutorial/blob/master/app/src/main/java/com/github/gorbin/asnetutorial/MainFragment.java))

```java
public static SocialNetworkManager mSocialNetworkManager;
/**
 * SocialNetwork Ids in ASNE:
 * 1 - Twitter
 * 2 - LinkedIn
 * 3 - Google Plus
 * 4 - Facebook
 * 5 - Vkontakte
 * 6 - Odnoklassniki
 * 7 - Instagram
 */
public static final int TWITTER = 1;
public static final int LINKEDIN = 2;
public static final int FACEBOOK = 4;

private Button facebook;
private Button twitter;
private Button linkedin;

public MainFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.main_fragment, container, false);
    ((MainActivity)getActivity()).getSupportActionBar().setTitle(R.string.app_name);
    // init buttons and set Listener
    facebook = (Button) rootView.findViewById(R.id.facebook);
    facebook.setOnClickListener(loginClick);
    twitter = (Button) rootView.findViewById(R.id.twitter);
    twitter.setOnClickListener(loginClick);
    linkedin = (Button) rootView.findViewById(R.id.linkedin);
    linkedin.setOnClickListener(loginClick);

    //Get Keys for initiate SocialNetworks
    String TWITTER_CONSUMER_KEY = getActivity().getString(R.string.twitter_consumer_key);
    String TWITTER_CONSUMER_SECRET = getActivity().getString(R.string.twitter_consumer_secret);
    String LINKEDIN_CONSUMER_KEY = getActivity().getString(R.string.linkedin_consumer_key);
    String LINKEDIN_CONSUMER_SECRET = getActivity().getString(R.string.linkedin_consumer_secret);

    //Chose permissions
    ArrayList<String> fbScope = new ArrayList<String>();
    fbScope.addAll(Arrays.asList("public_profile, email, user_friends"));
    String linkedInScope = "r_basicprofile+rw_nus+r_network+w_messages";

    //Use manager to manage SocialNetworks
    mSocialNetworkManager = (SocialNetworkManager) getFragmentManager().findFragmentByTag(SOCIAL_NETWORK_TAG);

    //Check if manager exist
    if (mSocialNetworkManager == null) {
        mSocialNetworkManager = new SocialNetworkManager();

        //Init and add to manager FacebookSocialNetwork
        FacebookSocialNetwork fbNetwork = new FacebookSocialNetwork(this, fbScope);
        mSocialNetworkManager.addSocialNetwork(fbNetwork);

        //Init and add to manager TwitterSocialNetwork
        TwitterSocialNetwork twNetwork = new TwitterSocialNetwork(this, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
        mSocialNetworkManager.addSocialNetwork(twNetwork);

        //Init and add to manager LinkedInSocialNetwork
        LinkedInSocialNetwork liNetwork = new LinkedInSocialNetwork(this, LINKEDIN_CONSUMER_KEY, LINKEDIN_CONSUMER_SECRET, linkedInScope);
        mSocialNetworkManager.addSocialNetwork(liNetwork);

        //Initiate every network from mSocialNetworkManager
        getFragmentManager().beginTransaction().add(mSocialNetworkManager, SOCIAL_NETWORK_TAG).commit();
        mSocialNetworkManager.setOnInitializationCompleteListener(this);
    } else {
        //if manager exist - get and setup login only for initialized SocialNetworks
        if(!mSocialNetworkManager.getInitializedSocialNetworks().isEmpty()) {
            List<SocialNetwork> socialNetworks = mSocialNetworkManager.getInitializedSocialNetworks();
            for (SocialNetwork socialNetwork : socialNetworks) {
                socialNetwork.setOnLoginCompleteListener(this);
                initSocialNetwork(socialNetwork);
            }
        }
    }
    return rootView;
}

private void initSocialNetwork(SocialNetwork socialNetwork){
    if(socialNetwork.isConnected()){
        switch (socialNetwork.getID()){
            case FACEBOOK:
                facebook.setText("Show Facebook profile");
                break;
            case TWITTER:
                twitter.setText("Show Twitter profile");
                break;
            case LINKEDIN:
                linkedin.setText("Show LinkedIn profile");
                break;
        }
    }
}

@Override
public void onSocialNetworkManagerInitialized() {
    //when init SocialNetworks - get and setup login only for initialized SocialNetworks
    for (SocialNetwork socialNetwork : mSocialNetworkManager.getInitializedSocialNetworks()) {
        socialNetwork.setOnLoginCompleteListener(this);
        initSocialNetwork(socialNetwork);
    }
}
```

MainFragment

  1. Request login for every social networks

    SocialNetwork socialNetwork = mSocialNetworkManager.getSocialNetwork(networkId);
    socialNetwork.requestLogin();
    

Full OnClickListener loginClick with checking connection of social network and if social network connected - show ProfileFragment.java on click

 **MainFragment.java**(full [source](https://github.com/gorbin/ASNETutorial/blob/master/app/src/main/java/com/github/gorbin/asnetutorial/MainFragment.java))

```java
private View.OnClickListener loginClick = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        int networkId = 0;
        switch (view.getId()){
            case R.id.facebook:
                networkId = FACEBOOK;
                break;
            case R.id.twitter:
                networkId = TWITTER;
                break;
            case R.id.linkedin:
                networkId = LINKEDIN;
                break;
        }
        SocialNetwork socialNetwork = mSocialNetworkManager.getSocialNetwork(networkId);
        if(!socialNetwork.isConnected()) {
            if(networkId != 0) {
                socialNetwork.requestLogin();
                MainActivity.showProgress(socialNetwork, "Loading social person");
            } else {
                Toast.makeText(getActivity(), "Wrong networkId", Toast.LENGTH_LONG).show();
            }
        } else {
            startProfile(socialNetwork.getID());
        }
    }
};

```
  1. After social network login form we got callback onLoginSuccess(int networkId) or onError(int networkId, String requestID, String errorMessage, Object data) - lets show profile if login success and show Toast on error

MainFragment.java(full source)

```java
@Override
public void onLoginSuccess(int networkId) {
    MainActivity.hideProgress();
    startProfile(networkId);
}

@Override
public void onError(int networkId, String requestID, String errorMessage, Object data) {
    MainActivity.hideProgress();
    Toast.makeText(getActivity(), "ERROR: " + errorMessage, Toast.LENGTH_LONG).show();
}

private void startProfile(int networkId){
    ProfileFragment profile = ProfileFragment.newInstannce(networkId);
    getActivity().getSupportFragmentManager().beginTransaction()
            .addToBackStack("profile")
            .replace(R.id.container, profile)
            .commit();
}

```
  1. In ProfileFragment.java get networkId from MainFragment.java

ProfileFragment.java(full source) ```java public static ProfileFragment newInstannce(int id) { ProfileFragment fragment = new ProfileFragment(); Bundle args = new Bundle(); args.putInt(NETWORK_ID, id); fragment.setArguments(args); return fragment; }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
    networkId = getArguments().containsKey(NETWORK_ID) ? getArguments().getInt(NETWORK_ID) : 0;
    
}
```
  1. Now via networkId we can get social network and request current user profile like:

    socialNetwork = MainFragment.mSocialNetworkManager.getSocialNetwork(networkId);
    socialNetwork.setOnRequestCurrentPersonCompleteListener(this);
    socialNetwork.requestCurrentPerson();

don't forget to implement OnRequestSocialPersonCompleteListener 13. After completing request we can use SocialPerson dadta to fill our profile view

ProfileFragment.java(full source) ```java @Override public void onRequestSocialPersonSuccess(int i, SocialPerson socialPerson) { MainActivity.hideProgress(); name.setText(socialPerson.name); id.setText(socialPerson.id); String socialPersonString = socialPerson.toString(); String infoString = socialPersonString.substring(socialPersonString.indexOf("{")+1, socialPersonString.lastIndexOf("}")); info.setText(infoString.replace(", ", "\n")); Picasso.with(getActivity()) .load(socialPerson.avatarURL) .into(photo); }

@Override
public void onError(int networkId, String requestID, String errorMessage, Object data) {
    MainActivity.hideProgress();
    Toast.makeText(getActivity(), "ERROR: " + errorMessage, Toast.LENGTH_LONG).show();
}
```

MainFragment
14. For logout you just need to use

socialNetwork.logout();
getActivity().getSupportFragmentManager().popBackStack();
  1. Truly, that's all - we integrate Facebook, Twitter and Linkedin and get user profile. You can add other social networks like Instagram or Google Plus just adding dependency for them and adding them to SocialNetworkManager like in step 8:
   GooglePlusSocialNetwork gpNetwork = new GooglePlusSocialNetwork(this);
   mSocialNetworkManager.addSocialNetwork(gpNetwork);

   InstagramSocialNetwork instagramNetwork = new InstagramSocialNetwork(this, INSTAGRAM_CLIENT_KEY, INSTAGRAM_CLIENT_SECRET, instagramScope);
   mSocialNetworkManager.addSocialNetwork(instagramNetwork);

And of course you can use any other request which we use bellow for them

  1. In this tutorial we make some more requests Share link and Get user friendslist

Let's share simple link via social network:

  • Setup share button

    share = (Button) rootView.findViewById(R.id.share);
    share.setOnClickListener(shareClick);
  • To share we need fill bundle and just request post link

    Bundle postParams = new Bundle();
    postParams.putString(SocialNetwork.BUNDLE_LINK, link);
    socialNetwork.requestPostLink(postParams, message, postingComplete);
  • And of course some actions to callback

     ```java
     private OnPostingCompleteListener postingComplete = new OnPostingCompleteListener() {
         @Override
         public void onPostSuccessfully(int socialNetworkID) {
             Toast.makeText(getActivity(), "Sent", Toast.LENGTH_LONG).show();
         }
    
         @Override
         public void onError(int socialNetworkID, String requestID, String errorMessage, Object data) {
             Toast.makeText(getActivity(), "Error while sending: " + errorMessage, Toast.LENGTH_LONG).show();
         }
     };
     ```
    
  • So OnClickListener shareClick is

     **ProfileFragment.java**(full [source](https://github.com/gorbin/ASNETutorial/blob/master/app/src/main/java/com/github/gorbin/asnetutorial/ProfileFragment.java))
    
      private View.OnClickListener shareClick = new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              AlertDialog.Builder ad = alertDialogInit("Would you like to post Link:", link);
              ad.setPositiveButton("Post link", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int id) {
                      if(networkId != MainFragment.TWITTER){
                          Bundle postParams = new Bundle();
                          postParams.putString(SocialNetwork.BUNDLE_LINK, link);
                          socialNetwork.requestPostLink(postParams, message, postingComplete);
                      } else {
                          socialNetwork.requestPostMessage(message + " " + link, postingComplete);
                      }
                  }
              });
              ad.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int i) {
                      dialog.cancel();
                  }
              });
              ad.setOnCancelListener(new DialogInterface.OnCancelListener() {
                  public void onCancel(DialogInterface dialog) {
                      dialog.cancel();
                  }
              });
              ad.create().show();
          }
      };
    
      private AlertDialog.Builder alertDialogInit(String title, String message){
          AlertDialog.Builder ad = new AlertDialog.Builder(getActivity());
          ad.setTitle(title);
          ad.setMessage(message);
          ad.setCancelable(true);
          return ad;
      }

Share

Here we make standard alert dialog to notify user that we want to share link and in PositiveButton we check if it is not Twitter(there are no method in twitter api to post link, but we can post message as message + link)

Let's get friendslist via social network:

  • Get social network id

  • Get SocialNetwork from Id and request get freinds

    ```java
    SocialNetwork socialNetwork = MainFragment.mSocialNetworkManager.getSocialNetwork(networkId);
    socialNetwork.setOnRequestGetFriendsCompleteListener(this);
    socialNetwork.requestGetFriends();
    ```
    

    don't forget to implement OnRequestGetFriendsCompleteListener

  • Get response

     ```java
     @Override
     public void OnGetFriendsIdComplete(int id, String[] friendsID) {
         ((MainActivity)getActivity()).getSupportActionBar().setTitle(friendsID.length + " Friends");
     }
    
     @Override
     public void OnGetFriendsComplete(int networkID, ArrayList<SocialPerson> socialPersons) {
         MainActivity.hideProgress();
         FriendsListAdapter adapter = new FriendsListAdapter(getActivity(), socialPersons, networkID);
         listView.setAdapter(adapter);
     }
    
     @Override
     public void onError(int networkId, String requestID, String errorMessage, Object data) {
         MainActivity.hideProgress();
         Toast.makeText(getActivity(), "ERROR: " + errorMessage, Toast.LENGTH_LONG).show();
     }
     ```
    

Friends

More detailed you can read in FriendsFragment.java

##Conclusion Using ASNE modules you can easily and quickly integrate any popular social networks and use common requests in your app. Of course library got more methods which you can use in your application. But in case if you want to use social network methods from SDK or API you can easily get accesstokens or get instancesof main object in your App

This is simple tutorial demom if you need more complex - check ASNE demo app

Codeproject article

Source code: Zip



ASNETutorial Android Arsenal Codeproject

https://github.com/gorbin/ASNE 库的简单示例项目

今天社交网络集成到您的Android应用程序是常见的做法 - 它使用户轻松登录到您的应用程序并分享他们的行为。有很多方法可以实现 - 通常开发人员添加原生社交网络SDK或为每个网络使用API​​。它通过安装的社交网络应用程序或本机对话框提供登录。你必须花时间和精力学习和使用不同的社交网络SDK。

如果您需要为您的应用添加一个社交网络怎么办?有时您必须重组或重做所有的整合。这导致创建和实现所有社交网络的通用接口的想法。幸运的是有一个开放源码的模块化库 ASNE ,可以让您选择必要的社交网络,并为最常用的应用提供完整的sdk和通用界面请求(登录,分享,朋友列表等)节省您的时间,并在将来简化添加其他网络。此外,您可以轻松地将任何其他社交网络添加为新模块 - 与其他模块中所做的相似。

在本教程中,您可以了解如何使用 ASNE模块将Facebook,Twitter轻松集成到Android应用程序中。这是非常基本的教程,登录,共享链接和显示朋友列表。

注册应用程序 - 获取应用程序的密钥 为了在您的应用程序中实现社交网络,您需要使用键来进行API调用。所以注册一个新的社交网络应用程序并获得密钥。检查小教程如何得到它:

要继续,您需要

  • Facebook应用程式ID
  • Twitter消费者密钥和消费者秘密
  • LinkedIn消费者密钥和消费者秘密
将Facebook,Twitter和LinkedIn整合到您的应用程序

  1. Create new Project in Android Studio

  2. Let's save our social network keys in values/strings.xml

    strings.xml(full source)

    <?xml version="1.0" encoding="utf-8"?>
       <resources>
           <string name="app_name">ASNE-tutorial</string>

       &lt;<span class="pl-ent">string</span> <span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>facebook_app_id<span class="pl-pds">&#34;</span></span>&gt;
           1646388738920557
       &lt;/<span class="pl-ent">string</span>&gt;
       &lt;<span class="pl-ent">string</span> <span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>twitter_consumer_key<span class="pl-pds">&#34;</span></span>&gt;
           BBQAUAVKYzmYtvEcNhUEvGiKd
       &lt;/<span class="pl-ent">string</span>&gt;
        byZzHPxE1tkGmnPEj5zUyc7MG464Q1LgNRcwbBJV1Ap86575os
    &lt;/<span class="pl-ent">string</span>&gt;
       &lt;<span class="pl-ent">string</span> <span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>linkedin_consumer_key<span class="pl-pds">&#34;</span></span>&gt;
           75ubsp337ll7sf
       &lt;/<span class="pl-ent">string</span>&gt;
       &lt;<span class="pl-ent">string</span> <span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>linkedin_consumer_secret<span class="pl-pds">&#34;</span></span>&gt;
           8DVk4hi3wvEyzjbh
       &lt;/<span class="pl-ent">string</span>&gt;
    

    </resources>

  3. Add permissions and meta data - open AndroidManifest.xml file and add uses-permission for INTERNET, ACCESS_NETWORK_STATE and add meta-data for facebook(add appId key)

    AndroidManifest.xml(full source)

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="asne_tutorial.githubgorbin.com.asne_tutorial" >

    &lt;<span class="pl-ent">uses-permission</span> <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>android.permission.INTERNET<span class="pl-pds">&#34;</span></span> /&gt;
    &lt;<span class="pl-ent">uses-permission</span> <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>android.permission.ACCESS_NETWORK_STATE<span class="pl-pds">&#34;</span></span>/&gt;
    
    &lt;<span class="pl-ent">application</span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">allowBackup</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>true<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">icon</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>@drawable/ic_launcher<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">label</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>@string/app_name<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">theme</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>@style/AppTheme<span class="pl-pds">&#34;</span></span> &gt;
        &lt;<span class="pl-ent">activity</span>
            <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>.MainActivity<span class="pl-pds">&#34;</span></span>
            <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">label</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>@string/app_name<span class="pl-pds">&#34;</span></span> &gt;
            &lt;<span class="pl-ent">intent-filter</span>&gt;
                &lt;<span class="pl-ent">action</span> <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>android.intent.action.MAIN<span class="pl-pds">&#34;</span></span> /&gt;
                &lt;<span class="pl-ent">category</span> <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>android.intent.category.LAUNCHER<span class="pl-pds">&#34;</span></span> /&gt;
            &lt;/<span class="pl-ent">intent-filter</span>&gt;
        &lt;/<span class="pl-ent">activity</span>&gt;
    
        &lt;<span class="pl-ent">meta-data</span>
            <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>com.facebook.sdk.ApplicationId<span class="pl-pds">&#34;</span></span>
            <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">value</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>@string/facebook_app_id<span class="pl-pds">&#34;</span></span>/&gt;
    &lt;/<span class="pl-ent">application</span>&gt;
    

    </manifest>

  4. Set dependencies for asne-modules:

    Open Project Structure => choose your module and open Dependencies => Add new library dependency

添加库依赖data-canonical-src

然后搜索 asne 并添加 asne-facebook,asne-twitter,asne-linkedin

search

或者只需将它们手动添加到 build.gradle

(p。 build.gradle ) / p>
apply plugin: 'com.android.application'

android {
   compileSdkVersion 19
   buildToolsVersion &#39;20.0.0&#39;

   defaultConfig {
       applicationId &#34;asne_tutorial.githubgorbin.com.asne_tutorial&#34;
       minSdkVersion 10
       targetSdkVersion 19
       versionCode 1
       versionName &#34;1.0&#34;
   }
   buildTypes {
       release {
           runProguard false
           proguardFiles getDefaultProguardFile(&#39;proguard-android.txt&#39;), &#39;proguard-rules.pro&#39;
       }
   }
}

dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:20.0.0' compile 'com.github.asne:asne-facebook:0.3.1' compile 'com.github.asne:asne-linkedin:0.3.1' compile 'com.github.asne:asne-twitter:0.3.1' }

  1. Lets create some layouts Just login buttons in main fragment main_fragment.xml(full source)
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFCCCCCC">

    &lt;<span class="pl-ent">Button</span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_width</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>fill_parent<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_height</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>wrap_content<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">text</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>Login via Facebook<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">id</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>@+id/facebook<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_gravity</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>center_horizontal<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">background</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>#3b5998<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_margin</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>8dp<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">textColor</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>#ffffffff<span class="pl-pds">&#34;</span></span> /&gt;
    &lt;<span class="pl-ent">Button</span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_width</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>fill_parent<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_height</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>wrap_content<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">text</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>Login via Twitter<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">id</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>@+id/twitter<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_gravity</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>center_horizontal<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">background</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>#55ACEE<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_margin</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>8dp<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">textColor</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>#ffffffff<span class="pl-pds">&#34;</span></span>/&gt;
    &lt;<span class="pl-ent">Button</span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_width</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>fill_parent<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_height</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>wrap_content<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">text</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>Login via LinkedIn<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">id</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>@+id/linkedin<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_gravity</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>center_horizontal<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">background</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>#287bbc<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_margin</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>8dp<span class="pl-pds">&#34;</span></span>
        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">textColor</span>=<span class="pl-s"><span class="pl-pds">&#34;</span>#ffffffff<span class="pl-pds">&#34;</span></span>/&gt;
    

    </LinearLayout>

为用户创建简单的个人资料卡 profile_fragment.xml (完整的来源< / a>)


</p>
<pre><code>    &lt;RelativeLayout
        android:layout_width=&#34;wrap_content&#34;
        android:layout_height=&#34;wrap_content&#34;
        android:layout_alignParentTop=&#34;true&#34;
        android:layout_alignParentLeft=&#34;true&#34;
        android:layout_alignParentStart=&#34;true&#34;
        android:layout_margin=&#34;8dp&#34;
        android:id=&#34;@+id/frame&#34;
        android:background=&#34;@color/dark&#34;&gt;

        &lt;RelativeLayout
            android:layout_width=&#34;fill_parent&#34;
            android:layout_height=&#34;wrap_content&#34;
            android:layout_alignParentTop=&#34;true&#34;
            android:layout_alignParentLeft=&#34;true&#34;
            android:layout_alignParentStart=&#34;true&#34;
            android:layout_margin=&#34;3dp&#34;
            android:id=&#34;@+id/card&#34;
            android:background=&#34;#FFFFFF&#34;&gt;

            &lt;ImageView
                android:layout_width=&#34;100dp&#34;
                android:layout_height=&#34;100dp&#34;
                android:id=&#34;@+id/imageView&#34;
                android:layout_margin=&#34;8dp&#34;
                android:padding=&#34;2dp&#34;
                android:background=&#34;@color/grey_light&#34;
                android:layout_alignParentTop=&#34;true&#34;
                android:layout_alignParentLeft=&#34;true&#34;
                android:layout_alignParentStart=&#34;true&#34;
                android:src=&#34;@drawable/user&#34;
                android:adjustViewBounds=&#34;true&#34;
                android:cropToPadding=&#34;true&#34;
                android:scaleType=&#34;centerCrop&#34;/&gt;

            &lt;TextView
                android:layout_width=&#34;wrap_content&#34;
                android:layout_height=&#34;wrap_content&#34;
                android:textAppearance=&#34;?android:attr/textAppearanceLarge&#34;
                android:text=&#34;NoName&#34;
                android:maxLines=&#34;3&#34;
                android:singleLine=&#34;false&#34;
                android:id=&#34;@+id/name&#34;
                android:padding=&#34;8dp&#34;
                android:layout_alignTop=&#34;@+id/imageView&#34;
                android:layout_toRightOf=&#34;@+id/imageView&#34;
                android:layout_toEndOf=&#34;@+id/imageView&#34;
                android:layout_alignParentRight=&#34;true&#34;
                android:layout_alignParentEnd=&#34;true&#34; /&gt;

            &lt;TextView
                android:layout_width=&#34;wrap_content&#34;
                android:layout_height=&#34;wrap_content&#34;
                android:text=&#34;null&#34;
                android:maxLines=&#34;3&#34;
                android:singleLine=&#34;false&#34;
                android:id=&#34;@+id/id&#34;
                android:padding=&#34;8dp&#34;
                android:layout_below=&#34;@+id/name&#34;
                android:layout_alignLeft=&#34;@+id/name&#34;
                android:layout_alignStart=&#34;@+id/name&#34; /&gt;

            &lt;TextView
                android:layout_width=&#34;wrap_content&#34;
                android:layout_height=&#34;wrap_content&#34;
                android:text=&#34;&#34;
                android:id=&#34;@+id/info&#34;
                android:padding=&#34;8dp&#34;
                android:layout_marginBottom=&#34;4dp&#34;
                android:layout_below=&#34;@+id/imageView&#34;
                android:layout_alignParentLeft=&#34;true&#34;
                android:layout_alignParentStart=&#34;true&#34; /&gt;

        &lt;/RelativeLayout&gt;
        &lt;LinearLayout
            android:layout_width=&#34;match_parent&#34;
            android:layout_height=&#34;wrap_content&#34;
            android:id=&#34;@+id/buttonLayout&#34;
            android:layout_below=&#34;@+id/card&#34;
            android:layout_alignParentLeft=&#34;true&#34;
            android:layout_alignParentRight=&#34;true&#34;
            android:gravity=&#34;center&#34;
            android:background=&#34;@color/grey_light&#34;&gt;

            &lt;Button
                android:layout_width=&#34;match_parent&#34;
                android:layout_height=&#34;match_parent&#34;
                android:text=&#34;Friends&#34;
                android:id=&#34;@+id/friends&#34;
                android:padding=&#34;8dp&#34;
                android:background=&#34;@color/dark&#34;
                android:layout_marginRight=&#34;1dp&#34;
                android:layout_weight=&#34;1&#34;
                android:textColor=&#34;#ffffffff&#34;/&gt;
            &lt;Button
                android:layout_width=&#34;match_parent&#34;
                android:layout_height=&#34;match_parent&#34;
                android:text=&#34;Share&#34;
                android:id=&#34;@+id/share&#34;
                android:padding=&#34;8dp&#34;
                android:background=&#34;@color/dark&#34;
                android:layout_weight=&#34;1&#34;
                android:textColor=&#34;#ffffffff&#34;/&gt;
        &lt;/LinearLayout&gt;
    &lt;/RelativeLayout&gt;

&lt;/ScrollView&gt;

并将社交网络颜色保存到

color.xml (完整来源 xml <?xml version =1.0encoding =utf-8?&gt; &lt;资源&gt; &lt; color name =grey_light&gt;#FFCCCCCC&lt; / color&gt; &lt; color name =dark&gt;#4b4b4b&lt; / color&gt; &lt; color name =facebook&gt;#3b5998&lt; / color&gt; &lt; color name =twitter&gt;#55ACEE&lt; / color&gt; &lt; color name =linkedin&gt;#287bbc&lt; / color&gt; &lt; / resources&gt;

  1. Let's setup MainActivity.java We should set up onActivityResult method to catch responses after requesting login

    MainActivity.java(full source)

   public static final String SOCIAL_NETWORK_TAG = "SocialIntegrationMain.SOCIAL_NETWORK_TAG";

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Fragment fragment = getSupportFragmentManager().findFragmentByTag(SOCIAL_NETWORK_TAG); if (fragment != null) { fragment.onActivityResult(requestCode, resultCode, data); } }

每个登录表单后,社交网络发送 onActivityResult ,我们应该检查它并发送到我们的 SocialNetworkManager ,将其传递给Right SocialNetwork

  1. Create MainFragment.java and begin transaction of this fragmetn in MainActivity.java

    MainActivity.java(full source)

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

    <span class="pl-k">if</span> (savedInstanceState <span class="pl-k">==</span> <span class="pl-c1">null</span>) {
        getSupportFragmentManager()<span class="pl-k">.</span>beginTransaction()
            .add(<span class="pl-smi">R</span><span class="pl-k">.</span>id<span class="pl-k">.</span>container, <span class="pl-k">new</span> <span class="pl-smi">MainFragment</span>())
            .commit();
    }
    

    }

  2. Integrating of any social network is simple:

    • Get SocialNetworkManager
    mSocialNetworkManager = (SocialNetworkManager) getFragmentManager().findFragmentByTag(MAinActivity.SOCIAL_NETWORK_TAG);
    • Get keys from values.xml - note Facebook appId we used in AndroidManifest.xml
    String TWITTER_CONSUMER_KEY = getActivity().getString(R.string.twitter_consumer_key);
    String TWITTER_CONSUMER_SECRET = getActivity().getString(R.string.twitter_consumer_secret);
    String TWITTER_CALLBACK_URL = "oauth://ASNE";
    String LINKEDIN_CONSUMER_KEY = getActivity().getString(R.string.linkedin_consumer_key);
    String LINKEDIN_CONSUMER_SECRET = getActivity().getString(R.string.linkedin_consumer_secret);
    String LINKEDIN_CALLBACK_URL = "https://asneTutorial";
    • Create chosen SocialNetworks with permissions
    ArrayList<String> fbScope = new ArrayList<String>();
    fbScope.addAll(Arrays.asList("public_profile, email, user_friends"));
    FacebookSocialNetwork fbNetwork = new FacebookSocialNetwork(this, fbScope);

    // permissions for twitter in developer twitter console TwitterSocialNetwork twNetwork = new TwitterSocialNetwork(this, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_CALLBACK_URL);

    String linkedInScope = "r_basicprofile+r_fullprofile+rw_nus+r_network+w_messages+r_emailaddress+r_contactinfo"; LinkedInSocialNetwork liNetwork = new LinkedInSocialNetwork(this, LINKEDIN_CONSUMER_KEY, LINKEDIN_CONSUMER_SECRET, LINKEDIN_CALLBACK_URL, linkedInScope);

    • Check if SocialNetworkManager is null init it and add SocialNetworks to it
    mSocialNetworkManager = new SocialNetworkManager();

    mSocialNetworkManager.addSocialNetwork(fbNetwork); mSocialNetworkManager.addSocialNetwork(twNetwork); mSocialNetworkManager.addSocialNetwork(liNetwork);

    //Initiate every network from mSocialNetworkManager getFragmentManager().beginTransaction().add(mSocialNetworkManager, MAinActivity.SOCIAL_NETWORK_TAG).commit(); mSocialNetworkManager.setOnInitializationCompleteListener(this);

    don't forget to implement SocialNetworkManager.OnInitializationCompleteListener

    • If SocialNetworkManager - come from another fragment where we already init it - get all initialized social networks and add to them necessary listeners
    if(!mSocialNetworkManager.getInitializedSocialNetworks().isEmpty()) {
        List<SocialNetwork> socialNetworks = mSocialNetworkManager.getInitializedSocialNetworks();
        for (SocialNetwork socialNetwork : socialNetworks) {
            socialNetwork.setOnLoginCompleteListener(this);
        }

    don't forget to implement OnLoginCompleteListener

    • Now we need to catch callback after initializing of SocialNetworks
    @Override
    public void onSocialNetworkManagerInitialized() {
        for (SocialNetwork socialNetwork : mSocialNetworkManager.getInitializedSocialNetworks()) {
            socialNetwork.setOnLoginCompleteListener(this);
            initSocialNetwork(socialNetwork);
        }
    }

    don't forget to implement OnLoginCompleteListener

从MainFragment的

完整 onCreateView onSocialNetworkManagerInitialized ,初始化并设置侦听器到按钮

MainFragment.java(full source)

public static SocialNetworkManager mSocialNetworkManager;
/**
 * SocialNetwork Ids in ASNE:
 * 1 - Twitter
 * 2 - LinkedIn
 * 3 - Google Plus
 * 4 - Facebook
 * 5 - Vkontakte
 * 6 - Odnoklassniki
 * 7 - Instagram
 */
public static final int TWITTER = 1;
public static final int LINKEDIN = 2;
public static final int FACEBOOK = 4;

private Button facebook;
private Button twitter;
private Button linkedin;

public MainFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.main_fragment, container, false);
    ((MainActivity)getActivity()).getSupportActionBar().setTitle(R.string.app_name);
    // init buttons and set Listener
    facebook = (Button) rootView.findViewById(R.id.facebook);
    facebook.setOnClickListener(loginClick);
    twitter = (Button) rootView.findViewById(R.id.twitter);
    twitter.setOnClickListener(loginClick);
    linkedin = (Button) rootView.findViewById(R.id.linkedin);
    linkedin.setOnClickListener(loginClick);

    //Get Keys for initiate SocialNetworks
    String TWITTER_CONSUMER_KEY = getActivity().getString(R.string.twitter_consumer_key);
    String TWITTER_CONSUMER_SECRET = getActivity().getString(R.string.twitter_consumer_secret);
    String LINKEDIN_CONSUMER_KEY = getActivity().getString(R.string.linkedin_consumer_key);
    String LINKEDIN_CONSUMER_SECRET = getActivity().getString(R.string.linkedin_consumer_secret);

    //Chose permissions
    ArrayList&lt;String&gt; fbScope = new ArrayList&lt;String&gt;();
    fbScope.addAll(Arrays.asList(&#34;public_profile, email, user_friends&#34;));
    String linkedInScope = &#34;r_basicprofile+rw_nus+r_network+w_messages&#34;;

    //Use manager to manage SocialNetworks
    mSocialNetworkManager = (SocialNetworkManager) getFragmentManager().findFragmentByTag(SOCIAL_NETWORK_TAG);

    //Check if manager exist
    if (mSocialNetworkManager == null) {
        mSocialNetworkManager = new SocialNetworkManager();

        //Init and add to manager FacebookSocialNetwork
        FacebookSocialNetwork fbNetwork = new FacebookSocialNetwork(this, fbScope);
        mSocialNetworkManager.addSocialNetwork(fbNetwork);

        //Init and add to manager TwitterSocialNetwork
        TwitterSocialNetwork twNetwork = new TwitterSocialNetwork(this, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
        mSocialNetworkManager.addSocialNetwork(twNetwork);

        //Init and add to manager LinkedInSocialNetwork
        LinkedInSocialNetwork liNetwork = new LinkedInSocialNetwork(this, LINKEDIN_CONSUMER_KEY, LINKEDIN_CONSUMER_SECRET, linkedInScope);
        mSocialNetworkManager.addSocialNetwork(liNetwork);

        //Initiate every network from mSocialNetworkManager
        getFragmentManager().beginTransaction().add(mSocialNetworkManager, SOCIAL_NETWORK_TAG).commit();
        mSocialNetworkManager.setOnInitializationCompleteListener(this);
    } else {
        //if manager exist - get and setup login only for initialized SocialNetworks
        if(!mSocialNetworkManager.getInitializedSocialNetworks().isEmpty()) {
            List&lt;SocialNetwork&gt; socialNetworks = mSocialNetworkManager.getInitializedSocialNetworks();
            for (SocialNetwork socialNetwork : socialNetworks) {
                socialNetwork.setOnLoginCompleteListener(this);
                initSocialNetwork(socialNetwork);
            }
        }
    }
    return rootView;
}

private void initSocialNetwork(SocialNetwork socialNetwork){
    if(socialNetwork.isConnected()){
        switch (socialNetwork.getID()){
            case FACEBOOK:
                facebook.setText(&#34;Show Facebook profile&#34;);
                break;
            case TWITTER:
                twitter.setText(&#34;Show Twitter profile&#34;);
                break;
            case LINKEDIN:
                linkedin.setText(&#34;Show LinkedIn profile&#34;);
                break;
        }
    }
}

@Override
public void onSocialNetworkManagerInitialized() {
    //when init SocialNetworks - get and setup login only for initialized SocialNetworks
    for (SocialNetwork socialNetwork : mSocialNetworkManager.getInitializedSocialNetworks()) {
        socialNetwork.setOnLoginCompleteListener(this);
        initSocialNetwork(socialNetwork);
    }
}

MainFragmentdata-canonical-src

  1. Request login for every social networks

    SocialNetwork socialNetwork = mSocialNetworkManager.getSocialNetwork(networkId);
    socialNetwork.requestLogin();
    

Full OnClickListener loginClick检查社交网络的连接,如果社交网络连接 - 点击

显示 ProfileFragment.java
 MainFragment.java(full source)

private View.OnClickListener loginClick = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        int networkId = 0;
        switch (view.getId()){
            case R.id.facebook:
                networkId = FACEBOOK;
                break;
            case R.id.twitter:
                networkId = TWITTER;
                break;
            case R.id.linkedin:
                networkId = LINKEDIN;
                break;
        }
        SocialNetwork socialNetwork = mSocialNetworkManager.getSocialNetwork(networkId);
        if(!socialNetwork.isConnected()) {
            if(networkId != 0) {
                socialNetwork.requestLogin();
                MainActivity.showProgress(socialNetwork, &#34;Loading social person&#34;);
            } else {
                Toast.makeText(getActivity(), &#34;Wrong networkId&#34;, Toast.LENGTH_LONG).show();
            }
        } else {
            startProfile(socialNetwork.getID());
        }
    }
};

  1. After social network login form we got callback onLoginSuccess(int networkId) or onError(int networkId, String requestID, String errorMessage, Object data) - lets show profile if login success and show Toast on error

MainFragment.java (完整

```java
@Override
public void onLoginSuccess(int networkId) {
    MainActivity.hideProgress();
    startProfile(networkId);
}

@Override public void onError(int networkId, String requestID, String errorMessage, Object data) { MainActivity.hideProgress(); Toast.makeText(getActivity(), "ERROR: " + errorMessage, Toast.LENGTH_LONG).show(); }

private void startProfile(int networkId){ ProfileFragment profile = ProfileFragment.newInstannce(networkId); getActivity().getSupportFragmentManager().beginTransaction() .addToBackStack("profile") .replace(R.id.container, profile) .commit(); }

</code></pre>
<ol start="11">
<li>In <code>ProfileFragment.java</code> get networkId from <code>MainFragment.java</code></li>
</ol>
<p> <strong> ProfileFragment.java </strong>(完整<a href =https://github.com/gorbin/ASNETutorial/blob/master/app/src/main/java/com/github/gorbin/ asnetutorial / ProfileFragment.java>源</a>)
```java
public static ProfileFragment newInstannce(int id){
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putInt(NETWORK_ID,id);
fragment.setArguments(args);
返回片段
} </p>
<pre><code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
    networkId = getArguments().containsKey(NETWORK_ID) ? getArguments().getInt(NETWORK_ID) : 0;
    
}

  1. Now via networkId we can get social network and request current user profile like:

    socialNetwork = MainFragment.mSocialNetworkManager.getSocialNetwork(networkId);
    socialNetwork.setOnRequestCurrentPersonCompleteListener(this);
    socialNetwork.requestCurrentPerson();

不要忘记实现 OnRequestSocialPersonCompleteListener 13.完成请求后,我们可以使用SocialPerson dadta来填写我们的个人资料视图

ProfileFragment.java(full source)

@Override
public void onRequestSocialPersonSuccess(int i, SocialPerson socialPerson) {
MainActivity.hideProgress();
name.setText(socialPerson.name);
id.setText(socialPerson.id);
String socialPersonString = socialPerson.toString();
String infoString = socialPersonString.substring(socialPersonString.indexOf(&#34;{&#34;)+1, socialPersonString.lastIndexOf(&#34;}&#34;));
info.setText(infoString.replace(&#34;, &#34;, &#34;\n&#34;));
Picasso.with(getActivity())
.load(socialPerson.avatarURL)
.into(photo);
}</p>
<pre><code>@Override
public void onError(int networkId, String requestID, String errorMessage, Object data) {
    MainActivity.hideProgress();
    Toast.makeText(getActivity(), &#34;ERROR: &#34; + errorMessage, Toast.LENGTH_LONG).show();
}

MainFragmentdata-canonical-src 14.注销你只需要使用

socialNetwork.logout();
getActivity().getSupportFragmentManager().popBackStack();
  1. Truly, that's all - we integrate Facebook, Twitter and Linkedin and get user profile. You can add other social networks like Instagram or Google Plus just adding dependency for them and adding them to SocialNetworkManager like in step 8:
   GooglePlusSocialNetwork gpNetwork = new GooglePlusSocialNetwork(this);
   mSocialNetworkManager.addSocialNetwork(gpNetwork);

InstagramSocialNetwork instagramNetwork = new InstagramSocialNetwork(this, INSTAGRAM_CLIENT_KEY, INSTAGRAM_CLIENT_SECRET, instagramScope); mSocialNetworkManager.addSocialNetwork(instagramNetwork);

当然,您可以使用我们在其中使用的任何其他请求

  1. In this tutorial we make some more requests Share link and Get user friendslist

通过社交网络分享简单链接

  • 设置共享按钮

     share  = 按钮  findViewById( R   id  share);
    共享 setOnClickListener(shareClick); 
  • 要分享我们需要填写包,只需要发布链接

      Bundle  postParams  =  =pl-k> new   Bundle ();
    postParams  putString( SocialNetwork    BUNDLE_LINK ,link);
    socialNetwork  requestPostLink(postParams,message,postingComplete); 
  • 当然还有一些回调的动作

     ```java
     private OnPostingCompleteListener postingComplete = new OnPostingCompleteListener(){
         @Override
         public void onPostSuccessfully(int socialNetworkID){
             Toast.makeText(getActivity(),Sent,Toast.LENGTH_LONG).show();
         }

         @Override      public void onError(int socialNetworkID,String requestID,String errorMessage,Object data){          Toast.makeText(getActivity(),发送时出错:+ errorMessage,Toast.LENGTH_LONG).show();      }  };  ```

  • 所以 OnClickListener shareClick是

    **前面的 ** ProfileFragment.java **(full [source](https://github.com/gorbin/ASNETutorial/blob/master/app/src/main/java/com/github/gorbin/asnetutorial /ProfileFragment.java))
      private  查看 pl-k>。  OnClickListener  shareClick  =   new   View  OnClickListener ()
           @覆盖
           public   void   onClick  pl-smi>查看 视图){
               AlertDialog    Builder  pl-k> =  alertDialogInit( 要发布链接:> ,链接);
              ad  setPositiveButton( 发​​布链接     DialogInterface  pl-smi> OnClickListener (){
                   public   void   onClick  pl-smi> DialogInterface  对话框 int   id ){
                       if (networkId !=   MainFragment  class =pl-c1>  TWITTER 
                           Bundle  postParams  =   new   Bundle ();
                          postParams  putString( SocialNetwork    BUNDLE_LINK ,link);
                          socialNetwork  requestPostLink(postParams,message,postingComplete);
                      }  else  {
                          socialNetwork  requestPostMessage(message  +       + 
                      }
                  }
              });
              ad  setNegativeButton( 取消   DialogInterface  ppt> OnClickListener (){
                   @覆盖
                   public   void   onClick  pl-smi> DialogInterface  对话框 int  ){
                      对话框 cancel();
                  }
              });
              ad  setOnCancelListener( new   DialogInterface  span class =pl-smi> OnCancelListener (){
                   public   void   onCancel  pl-smi> DialogInterface  对话框){
                      对话框 cancel();
                  }
              });
              ad  create()。
          }
      };

       private AlertDialog Builder alertDialogInit( String title, String message){        AlertDialog Builder pl-k> = AlertDialog Builder (getActivity());       广告 setTitle(title);       ad setMessage(message);       ad setCancelable( true );        return ad;   }

分享data-canonical-src

这里我们做出标准的警报对话框,通知用户我们想要分享链接,在PositiveButton我们检查它是否不是Twitter(在twitter api没有方法发布链接,但我们可以发布消息作为消息+链接)

通过社交网络

获取 friendslist
  • 获取社交网络ID

  • 从Id获取 SocialNetwork ,并请求get freinds

     java
    SocialNetwork socialNetwork = MainFragment.mSocialNetworkManager.getSocialNetwork(networkId);
    socialNetwork.setOnRequestGetFriendsCompleteListener(this);
    socialNetwork.requestGetFriends();
    
     

    不要忘记实现 OnRequestGetFriendsCompleteListener

  • 获取回应

     ```java
     @Override
     public void OnGetFriendsIdComplete(int id,String [] friendsID){
         ((MainActivity)getActivity())。getSupportActionBar()。setTitle(friendsID.length +Friends);
     }

     @Override  public void OnGetFriendsComplete(int networkID,ArrayList&lt; SocialPerson&gt; socialPersons){      MainActivity.hideProgress();      FriendsListAdapter adapter = new FriendsListAdapter(getActivity(),socialPersons,networkID);      listView.setAdapter(adapter);  }

     @Override  public void onError(int networkId,String requestID,String errorMessage,Object data){      MainActivity.hideProgress();      Toast.makeText(getActivity(),ERROR:+ errorMessage,Toast.LENGTH_LONG).show();  }  ```

朋友data-canonical-src

更详细的你可以阅读 FriendsFragment.java

结论 使用ASNE模块,您可以轻松,快速地集成任何流行的社交网络,并在应用程序中使用常见请求。当然,图书馆可以在您的应用程序中使用更多方法。但是,如果要使用SDK或API中的社交网络方法,您可以轻松获取访问权限或在应用程序中获取主对象的实例

如果您需要更复杂的API,检查ASNE演示程序

Codeproject文章

源代码: Zip




相关问题推荐