Android - LinkedIn Integration 教程
封面图
•
2025-11-01
•
Android开发
199
0
0
0
在 Android 应用中集成 LinkedIn(领英)功能,通常是为了让用户能够通过 LinkedIn 登录、分享内容或获取用户信息。以下是**Android 中实现 LinkedIn 集成的详细教程**,包括: 1. 注册 LinkedIn 应用 2. 添加依赖和配置权限 3. 实现登录功能(OAuth 2.0) 4. 获取用户信息 5. 分享内容到 LinkedIn --- ## 📌 第一步:注册 LinkedIn 应用 1. 访问 [LinkedIn Developer](https://www.linkedin.com/developers/) 2. 使用你的 LinkedIn 账号登录。 3. 点击 **"Create Application"** 4. 填写应用名称、描述、网站 URL(可以是 `https://example.com` 或你自己的域名) 5. 在 **"OAuth 2.0"** 部分: - 设置 **Redirect URI**(例如 `yourapp://linkedin`) - 注意保存 **Client ID** 和 **Client Secret** > ⚠️ 如果你使用的是测试环境,建议设置为 `http://localhost` 或 `https://localhost`。 --- ## 📌 第二步:添加依赖和配置 ### 1. 添加依赖(`build.gradle`) ```gradle dependencies { implementation 'com.google.android.material:material:1.9.0' implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.auth0.android:auth0:2.0.0' // 可选,用于简化 OAuth 流程 } ``` > 或者你可以使用官方提供的 SDK(如 `linkedin-android-sdk`),但目前 LinkedIn 官方不再维护该 SDK,推荐使用 OAuth 2.0 自行实现。 --- ## 📌 第三步:实现 LinkedIn 登录(OAuth 2.0) ### 1. 创建 Redirect URI Activity 创建一个 `RedirectActivity.kt`,用于接收 LinkedIn 的授权码: ```kotlin class RedirectActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_redirect) val uri = intent.data if (uri != null && uri.toString().startsWith("yourapp://linkedin")) { val code = uri.getQueryParameter("code") val state = uri.getQueryParameter("state") // 发起请求获取 access token getAccessToken(code) } } private fun getAccessToken(code: String?) { val clientId = "YOUR_CLIENT_ID" val clientSecret = "YOUR_CLIENT_SECRET" val redirectUri = "yourapp://linkedin" val retrofit = Retrofit.Builder() .baseUrl("https://www.linkedin.com/oauth/v2/") .addConverterFactory(GsonConverterFactory.create()) .build() val service = retrofit.create(OAuthService::class.java) val call = service.getToken( grantType = "authorization_code", code = code, redirectUri = redirectUri, clientId = clientId, clientSecret = clientSecret ) call.enqueue(object : Callback<AccessTokenResponse> { override fun onResponse(call: Call<AccessTokenResponse>, response: Response<AccessTokenResponse>) { if (response.isSuccessful) { val accessToken = response.body()?.access_token fetchUserInfo(accessToken) } else { Log.e("LinkedIn", "Failed to get access token") } } override fun onFailure(call: Call<AccessTokenResponse>, t: Throwable) { Log.e("LinkedIn", "Error: ${t.message}") } }) } private fun fetchUserInfo(accessToken: String?) { val retrofit = Retrofit.Builder() .baseUrl("https://api.linkedin.com/v2/") .addConverterFactory(GsonConverterFactory.create()) .build() val service = retrofit.create(UserService::class.java) val call = service.getUserInfo("me", "email", "id", "name", "picture-urls::(original)", accessToken) call.enqueue(object : Callback<UserResponse> { override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) { if (response.isSuccessful) { val user = response.body() Log.d("LinkedIn", "User: $user") } else { Log.e("LinkedIn", "Failed to get user info") } } override fun onFailure(call: Call<UserResponse>, t: Throwable) { Log.e("LinkedIn", "Error: ${t.message}") } }) } } ``` --- ## 📌 第四步:定义 Retrofit 接口 ### `OAuthService.kt` ```kotlin interface OAuthService { @FormUrlEncoded @POST("accessToken") fun getToken( @Field("grant_type") grantType: String, @Field("code") code: String?, @Field("redirect_uri") redirectUri: String, @Field("client_id") clientId: String, @Field("client_secret") clientSecret: String ): Call<AccessTokenResponse> } ``` ### `UserService.kt` ```kotlin interface UserService { @GET("people/~") fun getUserInfo( @Query("projection") projection: String, @Header("Authorization") authorization: String ): Call<UserResponse> } ``` --- ## 📌 第五步:定义数据模型类 ### `AccessTokenResponse.kt` ```kotlin data class AccessTokenResponse( val access_token: String, val expires_in: Int ) ``` ### `UserResponse.kt` ```kotlin data class UserResponse( val id: String, val firstName: FirstName, val lastName: LastName, val pictureUrls: PictureUrls ) data class FirstName( @SerializedName("localized") val localized: Map<String, String> ) data class LastName( @SerializedName("localized") val localized: Map<String, String> ) data class PictureUrls( @SerializedName("values") val values: List<PictureUrl> ) data class PictureUrl( val value: String ) ``` --- ## 📌 第六步:启动 LinkedIn 登录流程 在你的主 Activity 中,跳转到 LinkedIn 授权页面: ```kotlin val clientId = "YOUR_CLIENT_ID" val redirectUri = "yourapp://linkedin" val scope = "r_liteprofile r_emailaddress" val url = "https://www.linkedin.com/oauth/v2/authorization?" + "response_type=code" + "&client_id=$clientId" + "&redirect_uri=$redirectUri" + "&scope=$scope" val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) ``` --- ## 📌 第七步:处理回调 在 `AndroidManifest.xml` 中声明 `RedirectActivity` 并设置 scheme: ```xml <activity android:name=".RedirectActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="linkedin" android:scheme="yourapp" /> </intent-filter> </activity> ``` --- ## ✅ 总结 | 步骤 | 内容 | |------|------| | 1 | 注册 LinkedIn App,获取 Client ID / Secret | | 2 | 添加 Retrofit 依赖 | | 3 | 实现 OAuth 登录流程 | | 4 | 获取 Access Token | | 5 | 获取用户信息 | | 6 | 处理回调并显示用户信息 | --- ## 🔧 注意事项 - **安全问题**:不要将 Client Secret 放在客户端代码中,建议后端处理 Token 获取。 - **权限范围**:根据需求选择合适的 Scope(如 `r_liteprofile`, `r_emailaddress`)。 - **Token 过期**:LinkedIn 的 Access Token 有有效期,需要处理刷新机制。 --- 如果你希望我提供完整项目模板或更详细的代码示例,请告诉我!
上一篇:
android ListView详解
下一篇:
android studio 修改项目名称
标题录入,一次不能超过6条
留言
评论