1. 集成Line登陸
1. project build.gradle
buildscript {
......
dependencies {
classpath 'com.android.tools.build:gradle:3.3.1'
......
}
}
allprojects {
repositories {
jcenter()
......
}
}
複製代碼
2. module build.gradle
android {
defaultConfig {
......
minSdkVersion 17
......
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
......
}
dependencies {
......
implementation 'com.linecorp:linesdk:5.0.1'
}
複製代碼
3. LoginActivity.class
集成登陸功能
- 先驗證token是否有效,token有效則能夠使用
LineApiClient
獲取token和userId;token無效須要跳轉到Line app登陸(若是沒安裝Line app則打開瀏覽器進行網頁受權)
- token有效狀態下,用戶信息均可以經過LineApiClient獲取。
- LineApiClient 的方法由於須要訪問網絡,因此都須要在子線程調用。
public class LoginActivity extends Activity {
private static final int REQUEST_CODE = 1000;
private static LineApiClient lineApiClient;
public static LineApiClient getLineApiClient(Context context) {
if (lineApiClient == null) {
synchronized (LoginActivity.class) {
if (lineApiClient == null) {
LineApiClientBuilder apiClientBuilder = new LineApiClientBuilder(context, Constants.LINE_CHANNEL_ID);
lineApiClient = apiClientBuilder.build();
}
}
}
return lineApiClient;
}
public void login() {
AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
try {
if (getLineApiClient(LoginActivity.this).verifyToken().isSuccess()) {
String accessToken = getLineApiClient(LoginActivity.this).getCurrentAccessToken().getResponseData().getTokenString();
LineProfile profile = getLineApiClient(LoginActivity.this).getProfile().getResponseData();
String userId = profile.getUserId();
loginSuccess(userId, accessToken);
return;
}
} catch (Exception e) {
e.printStackTrace();
}
try{
LineAuthenticationParams params = new LineAuthenticationParams.Builder().scopes(Arrays.asList(Scope.PROFILE)).build();
Intent loginIntent = LineLoginApi.getLoginIntent(activity, Constants.LINE_CHANNEL_ID, params);
startActivityForResult(loginIntent, REQUEST_CODE);
} catch(Exception e) {
e.printStackTrace();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != REQUEST_CODE) {
return;
}
LineLoginResult result = LineLoginApi.getLoginResultFromIntent(data);
switch (result.getResponseCode()) {
case SUCCESS:
try {
String accessToken = result.getLineCredential().getAccessToken().getTokenString();
String userId = result.getLineProfile().getUserId();
String displayName = result.getLineProfile().getDisplayName();
} catch (Exception e) {
e.printStackTrace();
}
break;
case CANCEL:
break;
default:
}
}
public void logOut() {
AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
try {
getLineApiClient(LoginActivity.this).logout();
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
複製代碼
開發中遇到的問題和解決方案都在代碼寫了註釋。