Android Facebook and Twitter share

Source: Internet
Author: User
Tags jcenter

1. Background

At the beginning of the year, the company's project had a new need to add Facebook and Twitter to the English version of the app.

2. Completion of the situation

Due to the urgency of this project, it took a week to develop this feature from pre-research to access. Later, after the first official English version, the time is not so urgent, the original use of the third-party library of Twitter sharing, rewritten, replaced by the official Twitter SDK access function, a week, so from the beginning of the preliminary research to the final version, the total time spent two weeks.

3. Pre-research and Access 3.1 Facebook

When I was in the pre-study on Facebook, it seemed to me that there was no difficult place and everything went well. Then look, with the author's memories, difficulties and problems may slowly surfaced.

Preparatory work:

1) from the above address can be downloaded to the Facebook official SDK;

2) Choose the Add a new app from your Account drop-down menu, then follow the inside steps to get it done, and you'll end up with a Facebook app id;

3) from the https://developers.facebook.com/docs/android/getting-started, you can see

Then to execute the place where one of the two command lines can be executed, you can get a public key and fill this out (note that the above command cannot be executed under most windows, so I recommend that you install a simulator similar to the one that can execute Linux commands)

That's all there is to get ready for, so here's the code access step.

1) Integrate the Facebook SDK into the project: put the Facebook SDK package that you downloaded in the preparation to the project, and then add the code to the Gralde file

Compile (name: ' facebook-android-sdk-4.10.0 ', ext: ' AAR ')

2) Add in Androidmanifest.xml

                

The app_id is the value obtained in the second step.

3) In the beginning of your main program, or your own rewrite of the Application class OnCreate () to add:

Facebooksdk.sdkinitialize (Getapplicationcontext ());

4) Build the content you want to share and call the share code,

Sharelinkcontent.builder Sharelinkcontentbuilder = new Sharelinkcontent.builder (); Sharelinkcontentbuilder.setcontentdescription (). Setcontenttitle (). Setcontenturl (); Sharelinkcontent sharelinkcontent = Sharelinkcontentbuilder.build (); if (Sharedialog.canshow (ShareLinkContent.class ) {sharedialog.show (Activity) Mcontext, sharelinkcontent);}

So that's pretty much what Facebook shares. If the reader can follow the author to this step, I believe that the goal is near.

3.2 Twitter

Next, I want to say a talk about the process and experience of Twitter sharing. Here I only introduce the use of official Twitter files to access Twitter features, as to how to use the third-party library to complete, the next time you are free to write another blog it. I think Twitter is a lot more complicated than Facebook's shared access. The operation involved is also more cumbersome than Facebook, but whatever, the author at this time can record this blog, finally can explain this thing passed, no matter what problems encountered, but also finally solved.

Detour

Things don't always go well in the direction we envision. This is especially evident in the author's Twitter-sharing process. First of all, I start by looking at the way the Web page to check the information. The first time I went to Twitter, the official introduction is at the following address Https://dev.twitter.com/oauth, where the main introduction is how the user access to the Twitter platform licensing method. Of course, the Twitter platform has an authorization process when the user logs in, but sometimes we don't see them as usual. So I went down this road, and then walked into the open source authorization code. Because this is a detour, so the author only introduced here, do not go forward, but if the reader can go all the way, it is too powerful. The author does not want to continue.

Path

Detour is still a little bit better, after all, life is not long.

https://docs.fabric.io/This site is the official Twitter document, interested can be viewed by themselves. I mainly introduce myself according to this document, and successfully carry out the steps of Twitter sharing.

Preparatory work:

1) Install a fabric plugin for your Android studio: Just open the plugins under Settings in Android Studio and a fabric for Android studio can be installed;

2) to https://apps.twitter.com/in the Create new app, follow the steps in the walk will get an app key and an app secret, note that if you want to push the function, then in this step, Do not forget to select Read, Write and Access Direct messages this radio button;

That's the point of getting ready for work.

Buildscript {  repositories {    jcenter ()    maven {URL ' https://maven.fabric.io/public '}  }  dependencies {    classpath ' com.android.tools.build:gradle:1.5.0 '    //The Fabric Gradle plugin uses an open ended VE Rsion to react    //quickly to Android tooling updates    classpath ' io.fabric.tools:gradle:1.+ '  }}apply plugin: ' Com.android.application '//put Fabric plugin after Android pluginapply plugin: ' io.fabric ' repositories {    jcenter ( )    maven {URL ' https://maven.fabric.io/public '}}


Copy this section of code to the first line of the main program's BUILD.GRADLD, where we declare a MAVEN library from which we can proceed with the subsequent download of the package.

Compile (' Com.twitter.sdk.android:twitter:[email protected] ') {        transitive = true;    }    Compile (' Com.twitter.sdk.android:tweet-composer:[email protected] ') {        transitive = true;    }    Compile (' Com.crashlytics.sdk.android:crashlytics:[email protected] ') {        transitive = true;    }    Compile (' Com.twitter.sdk.android:tweet-ui:[email protected] ') {        transitive = true;    }


Copy this section of code into the file's dependencies to download the package. You can see a package that has nothing to do with Twitter, like Crashlytics. However, the author will be listed here, the lack of it or not, at least the program does not compile properly.

In the main program directory, create a file named Fabric.properties inside the Write

apisecret= secretapikey= in preparation for the work of the key


Here, this file will not have to move, wait for the plugin to be used, this file is automatically updated and replace the original secret value, these are normal.

The next step is to access the code.

1) Add in Androidmanifest.xml

Note that this value can not be changed, the direct copy can be;
2) in the beginning of their main program, or in the rewritten application class of OnCreate () to add

Twitterauthconfig authconfig = new Twitterauthconfig (Constants.twitter_api_key, Constants.twitter_api_secret); Fabric.with (This, new Twitter (authconfig)); Fabric.with (This, new Twittercore (authconfig), New Tweetui ()); Fabric.with (This, new Twittercore (authconfig), New Tweetcomposer (), New Crashlytics ());

This is to load your authorization information;

3) If your project is to be confused, add it in the obfuscation code

-dontwarn Com.squareup.okhttp.**-dontwarn Com.google.appengine.api.urlfetch.**-dontwarn Rx.**-dontwarn retrofit.** -keepattributes signature-keepattributes *annotation*-keep class com.squareup.okhttp.** {*;} -keep interface com.squareup.okhttp.** {*;} -keep class retrofit.** {*;} -keepclasseswithmembers class * {    @retrofit. http.*;}


4) Write the official Twitter login button to your own layout file.


And in the program can over Findviewbyid () find this button, by the following method

Loginbutton = (Twitterloginbutton) Findviewbyid (R.id.login_button);        Btnshowtweet = (Button) Findviewbyid (R.id.btn_show_tweet);        Lltweets = (linearlayout) Findviewbyid (r.id.ll_tweets);        Btnshowtweet.setonclicklistener (this);                Loginbutton.setcallback (New Callback () {@Override public void success (result result) { Do something with result, which provides a twittersession for making API calls Twitterauthtoken autht                Oken = Result.data.getAuthToken ();                String token = Authtoken.token;                String secret = Authtoken.secret;                Toast.maketext (mainactivity.this, token + "" + Secret, Toast.length_long). Show ();                        Compose a tweet tweetcomposer.builder Builder = new Tweetcomposer.builder (mainactivity.this)                        . Text ("Just setting up my Fabric.")                . Image (Getimguri ());                Builder.show (); LOad tweets//tweetutils.loadtweets (tweetids, New callback> () {//@Override//                            public void Success (Result> Result) {//for (Tweet tweet:result.data) {//                    Lltweets.addview (New Tweetview (Mainactivity.this, tweet));//}//                    }////@Override//public void failure (Twitterexception e) {////                }//                }); App card//final Twittersession session = Twittercore.getinstance (). Getsessionmanager (). Getactivesession ( );//FINAL card = new Card.appcardbuilder (mainactivity.this). Imageuri (Getimguri ()). Googleplayid ("COM.M Edzone.twitterpic "). Build ();//FINAL Intent Intent = new Composeractivity.builder (mainactivity.this). Sessio            N (session). Card. Createintent ();//startactivity (intent); } @OveRride public void failure (Twitterexception exception) {//does something on failure                Toast.maketext (Mainactivity.this, "Error", Toast.length_long). Show ();            LOG.D ("HSC", Exception.getmessage ());    }        }); } @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityr        Esult (Requestcode, ResultCode, data);        Pass the activity result to the login button.    Loginbutton.onactivityresult (Requestcode, ResultCode, data); }

It is important to note that your code should be written inside success () or your login information will be lost, of course, if the reader can find a solution, naturally no

Android Facebook and Twitter share

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.