这是 https://dev.twitter.com/twitterkit/android/overview
的开发者文档,
这是 https://apps.twitter.com 注册开发者账号
注意都要翻墙哦,
本人第一次写登录与分享,就写Twitter ,给我的感觉是Twitter的开发文档好坑好坑好坑,当我百度和google时发现他们初始化都不太一样,官方给的文档写出来连按钮都不能点击,我也是醉了.
还有就是国内的Twitter的文章好少,没多少还基本一样,看国外的吧,找到一个详细的要用那个 fabric的 结果搞进去后发现里面不知道怎么没Twitter的选项了,不知道什么原因,没有去深究,然后在github上找找到之前那个花了三天时间并看源码写出Twitter登录的那个哥们的代码,然后改了改跑起来了
这里有个坑就是当点击登录按钮时要翻墙,所以哥们你还是去在手机安装一个蓝灯吧
先登录开发者账号吧
我建议用手机号进去了在绑定邮箱,尽量把信息填全一点,以减小被封的几率,我在Facebook用邮箱注册进去看着看着就被封了,要我照片,我当然不给就在网上随便搜了一张发过去过两天账号永久
点击 create new app
Paste_Image.png第一个是应用名称,下一个是创建应用的说明,你应用的网址和回调网址,两个网址对于只写一个dome来说没什么用,你看着办
Paste_Image.png开发协议打钩 点击按钮
账号好了就来写代码了
app的build.gradle
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
// These docs use an open ended version so that our plugin
// can be updated quickly in response to Android tooling updates
// We recommend changing it to the latest version from our changelog:
// https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
repositories {
maven { url 'https://maven.fabric.io/public' }
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "br.com.carinatiemiyoshida.twitterdemonumberone"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
// compile 'com.android.support.constraint:constraint-layout:1.0.0'
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:25.3.1'
compile 'com.squareup.picasso:picasso:2.3.2'
compile('com.twitter.sdk.android:twitter:2.3.2@aar') {
transitive = true;
}
}
Paste_Image.png
清单文件的代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.com.carinatiemiyoshida.twitterdemonumberone">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- <meta-data
android:name="io.fabric.ApiKey"
android:value="f1f66542f826a25bb075924b95a22d09db87497e" />-->
</application>
</manifest>
activity_main的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.twitter.sdk.android.core.identity.TwitterLoginButton
android:id="@+id/twitter_login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<ImageView
android:id="@+id/imageView"
android:layout_marginTop="20dp"
android:layout_width="100sp"
android:layout_height="100sp" />
<TextView
android:id="@+id/txtDetails"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="shareToTwitter"
android:text="Twitter分享"
android:textAllCaps="false" />
</LinearLayout>
MainActivity的代码:
package br.com.carinatiemiyoshida.twitterdemonumberone;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
import com.twitter.sdk.android.core.models.User;
import com.twitter.sdk.android.tweetcomposer.TweetComposer;
import java.net.MalformedURLException;
import java.net.URL;
import io.fabric.sdk.android.Fabric;
import retrofit2.Call;
public class MainActivity extends AppCompatActivity {
private static final String TWITTER_KEY = "这里是API key";
private static final String TWITTER_SECRET = "这里是API Secret";
private static String LAG = "-----------MainActivity";
private TwitterLoginButton loginButton;
private ImageView imageView;
private TextView txtDetails;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
setContentView(R.layout.activity_main);
loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
imageView = (ImageView) findViewById(R.id.imageView);
txtDetails = (TextView) findViewById(R.id.txtDetails);
Log.e(LAG,"第一步");
loginButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
Log.e(LAG,"第二步");
TwitterSession session = result.data;
final String userName = session.getUserName();
//String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Call<User> user = Twitter.getApiClient(session).getAccountService().verifyCredentials(true, false);
user.enqueue(new Callback<User>() {
@Override
public void success(Result<User> result) {
Log.e(LAG,"第3步");
User userInfo = result.data;
String email = userInfo.email;
String description = userInfo.description;
String location = userInfo.location;
userInfo.getId();
int friendsCount = userInfo.friendsCount;
int favouritesCount = userInfo.favouritesCount;
int followersCount = userInfo.followersCount;
Picasso.with(getApplicationContext())
.load(userInfo.profileImageUrl)
.into(imageView);
Log.e(LAG,"------------ "+userInfo.profileImageUrl);
StringBuilder sb = new StringBuilder();
sb.append("User Name: "+ userName);
sb.append("\n");
sb.append("Email: "+ email);
sb.append("\n");
sb.append("Description: "+ description);
sb.append("\n");
sb.append("Location: "+ location);
sb.append("\n");
sb.append("FriendsCount: "+ friendsCount);
sb.append("\n");
sb.append("FavouritesCount: "+ favouritesCount);
sb.append("\n");
sb.append("FollowersCount: "+ followersCount);
txtDetails.setText(sb.toString());
}
@Override
public void failure(TwitterException exception) {
Log.e(LAG,"第4步");
}
});
loginButton.setVisibility(View.INVISIBLE);
//Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException exception) {
Log.e(LAG,"第5步");
Log.e("TwitterKit", "Login with Twitter failure", exception);
Log.e("BLA: ", exception.getMessage());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e(LAG,"第6步");
loginButton.onActivityResult(requestCode, resultCode, data);
}
/**
* 分享到twitter
* 若未安装twitter客户端,则会跳转到浏览器
*
* @param view
*/
public void shareToTwitter(View view) {
//这里分享一个链接,更多分享配置参考官方介绍:https://dev.twitter.com/twitterkit/android/compose-tweets
try {
TweetComposer.Builder builder = new TweetComposer.Builder(MainActivity.this)
.url(new URL("https://www.google.com/"));
builder.show();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
MyResultReceiver的代码:
package br.com.carinatiemiyoshida.twitterdemonumberone;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.twitter.sdk.android.tweetcomposer.TweetUploadService;
/**
* Created by and2long on 2017/6/25.
* Twitter的分享结果会在这里接受到,在此做相应的业务逻辑
*/
public class MyResultReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (TweetUploadService.UPLOAD_SUCCESS.equals(intent.getAction())) {
// success Twitter分享成功的回调
final Long tweetId = intent.getExtras().getLong(TweetUploadService.EXTRA_TWEET_ID);
} else {
// failure
final Intent retryIntent = intent.getExtras().getParcelable(TweetUploadService.EXTRA_RETRY_INTENT);
}
}
}
注意手机要翻墙哦
对了这是本人github地址: https://github.com/liang9/LoginShareTwitter
如果你觉得这篇文章对你有所帮助,请您点击一下喜欢以表示鼓励,谢谢.
还有就是如果文章哪里有问题可以说出来大家一起互相交流交流.
网友评论