flutter端创建MethodChannel类
import 'package:flutter/services.dart';//MethodChannel
const methodChannel = const MethodChannel('com.flutter.demo.MethodChannel');class FlutterMethodChannel {/** MethodChannel flutter给原生发信息* 在方法通道上调用方法invokeMethod* methodName 方法名称* params 发送给原生的参数* res 原生发给Flutter的参数*/static Future<Map> invokeNativeMethod(String methodName,[Map params]) async {var res;try {if (params == null) {res = await methodChannel.invokeMethod('$methodName');} else {res = await methodChannel.invokeMethod('$methodName', params);}} catch (e) {res = {'Failed': e.toString()};}return res;}/** MethodChannel* 接收methodHandler 接收原生给flutter发送的信息*/static void methodHandlerListener(Future<dynamic> Function(MethodCall call) handler) {methodChannel.setMethodCallHandler(handler);}
}
android端
import android.annotation.SuppressLint
import android.app.Activity
import android.util.Log
import androidx.annotation.Nullable
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.xingin.xhssharesdk.XhsShareSdkTools
import com.xingin.xhssharesdk.callback.XhsShareCallback
import com.xingin.xhssharesdk.callback.XhsShareRegisterCallback
import com.xingin.xhssharesdk.core.XhsShareSdk
import com.xingin.xhssharesdk.model.config.XhsShareGlobalConfig
import com.xingin.xhssharesdk.model.sharedata.*
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import java.lang.reflect.Type
import java.util.*
import java.util.ArrayList
import java.util.Objects
import kotlin.concurrent.timerTaskclass MethodChannelDemo(messenger: BinaryMessenger, var activity : Activity) : MethodCallHandler {private var channel: MethodChannelprivate var count = 0init {channel = MethodChannel(messenger,"com.flutter.demo.MethodChannel") //通道标识两端要保持一致channel.setMethodCallHandler(this)/*channel.setMethodCallHandler{call, result ->if (call.method == "sendData"){}}*/}///Flutter端调用invokeMethod方法的回调override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {if (call.method == "sendData") {var articleTitle = call.argument("title") as String?var articleContent = call.argument("articleContent") as String?val articlePicJsonArray = call.argument("articlePic") as String?val articleType = call.argument("articleType") as Int?// val jsonArray = call.argument("articlePic") as ArrayList<Object>?// val jsonArray = call.argument("articlePic") as List<Any>?// val jsonArray = call.argument("articlePic") as List<Map<String, Any>>?Log.i("onMethodCall","title= $articleTitle ")Log.i("onMethodCall","articleContent= $articleContent ")Log.i("onMethodCall","articleType= $articleType ")Log.i("onMethodCall","articlePic= $articlePicJsonArray ")val gson = Gson()/* val listType: Type = object : TypeToken<List<ArticlePic>>() {}.typeval articlePicList : List<ArticlePic?> = gson.fromJson(articlePicJsonArray, listType)Log.i("onMethodCall","articlePicList type = ${articlePicList[0]?.type} ")Log.i("onMethodCall","articlePicList url = ${articlePicList[0]?.url} ")*/val listType: Type = object : TypeToken<List<String>>() {}.typeval articlePicList : List<String?> = gson.fromJson(articlePicJsonArray, listType)Log.i("onMethodCall","articlePicList = ${articlePicList.size} ")var map = mapOf("title" to "$articleTitle", "articleContent" to "$articleContent", "articlePic" to "$articlePicList")initXhsSDK(articleTitle,articleContent,articlePicList,articleType)result.success(map)}}///Native 端主动发送数据给 Flutter时,Native 端代码需要在主线程中执行fun invokeNativeMethod(methodName : String,params : Map<String,*>){activity.runOnUiThread {channel.invokeMethod(methodName, params)}//销毁}fun startTimer() {var timer = Timer().schedule(timerTask {activity.runOnUiThread {var map = mapOf("count" to count++)channel.invokeMethod("methodToFlutter", map)}}, 0, 1000)}//小红书分享sdkprivate fun initXhsSDK(articleTitle : String?, articleContent: String?, articlePicList : List<String?>, articleType : Int?){Log.i("init","sendData init xhs")XhsShareSdk.registerApp(activity.applicationContext, "小红书appkey",XhsShareGlobalConfig().setEnableLog(true).setClearCacheWhenShareComplete(true),object : XhsShareRegisterCallback {override fun onSuccess() {Log.i("xhs","注册成功")// print( "onSuccess: 注册成功!")}override fun onError(errorCode: Int,errorMessage: String,@Nullable exception: Exception?) {Log.i("xhs","注册失败!errorCode: $errorCode errorMessage: $errorMessage exception: $exception")//print( "onError: 注册失败!errorCode: $errorCode errorMessage: $errorMessage exception: $exception")}})var imageUrlList : MutableList<XhsImageResourceBean?> = ArrayList()if(articleType == 1){articlePicList.forEach{ element ->imageUrlList.add(XhsImageResourceBean.fromUrl(element))}}var isInstalled = XhsShareSdkTools.isXhsInstalled(activity.applicationContext)if(isInstalled){var note : XhsNote? = XhsNote()activity.runOnUiThread {if(articleType == 1){note = XhsNote().apply {title = "$articleTitle"content = "$articleContent"/* imageInfo = XhsImageInfo(listOf(// XhsImageResourceBean.fromUrl("https://zmkx.oss-cn-hangzhou.aliyuncs.com/oss/client/user/1684727167914-6443e07877e247e8a360fa293c8bc0e4..png")// XhsImageResourceBean.fromUrl("/sdcard/Picture/1621565875992.jpg")))*/imageInfo = XhsImageInfo(imageUrlList)}}else if(articleType == 2){note = XhsNote().apply {title = "$articleTitle"content = "$articleContent"videoInfo = XhsVideoInfo(XhsVideoResourceBean.fromUrl(articlePicList[0]), // 视频XhsImageResourceBean.fromUrl(articlePicList[1]) // 封面)}}else {note = XhsNote().apply {title = "$articleTitle"content = "$articleContent"}}val sessionId = XhsShareSdk.shareNote(activity.applicationContext, note)XhsShareSdk.setShareCallback(object : XhsShareCallback {override fun onSuccess(p0: String?) {TODO("Not yet implemented")Log.i("xhs", "onSuccess: 分享成功!!! $p0")var map = mapOf("shareCallback" to true)channel.invokeMethod("xhsShareCallback", map)XhsShareSdk.setShareCallback(null)}override fun onError(p0: String, p1: Int, p2: String, p3: Throwable?) {TODO("Not yet implemented")Log.i("xhs", "onSuccess: 分享失败!!!")var map = mapOf("shareCallback" to true)channel.invokeMethod("xhsShareCallback", map)XhsShareSdk.setShareCallback(null)}})}}}
}
在MainActivity.kt中配置通道
package cn.adazon.atuiimport android.os.Build
import android.os.Bundle
import androidx.annotation.NonNull
/*import com.huawei.agconnect.common.network.AccessNetworkManager
import com.huawei.hms.analytics.HiAnalytics
import com.huawei.hms.analytics.HiAnalyticsTools*/
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrantclass MainActivity : FlutterActivity() {override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {GeneratedPluginRegistrant.registerWith(flutterEngine)MethodChannelDemo(flutterEngine.dartExecutor.binaryMessenger,activity)}/*** 设置状态栏沉浸式透明(修改flutter状态栏黑色半透明为全透明)*/override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){window.statusBarColor=0}}
}
小红书sdk配置
- 从小红书分享开放平台下载sdk
- 将.arr包复制到libs文件夹下
- 引入.arr包
在android>app目录下的build.gradle中配置implementation fileTree(dir: 'libs', includes: ['*.aar'])
另一种引入方式
在android目录下的build.gradle中配置flatDir { dir 'libs' }
android>app>build.gradle中配置implementation(name:'xhssharesdk-1.1.6', ext:'aar')