如果有人在使用Promise的React Native模块中使用Kotlin,请参考以下代码:
import android.app.Activity
import android.content.Intent
import android.util.Log
import com.facebook.react.bridge.*
import com.onboardinglib.HostActivity
class ConsistyOnboarding (reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext) {
private val CODE = 999
private var promise: Promise? = null
private val reContext: ReactApplicationContext? = reactContext
fun dumpIntent(intent: Intent) {
LogPrint("Bundle data", "Dumping intent start")
val bundleData = intent.extras
if (bundleData != null) {
for (key in bundleData.keySet()) {
LogPrint(
"Bundle data-->",
key + " : " + if (bundleData[key] != null) bundleData[key] else "NULL"
)
}
}
}
override fun getName(): String {
return "ConsistyOnboarding"
}
private val mActivityEventListener: ActivityEventListener =
object : BaseActivityEventListener() {
override fun onActivityResult(
activity: Activity,
requestCode: Int,
resultCode: Int,
data: Intent
) {
LogPrint("mActivityEventListener", "Started")
if (data == null) {
resolve("01", "No action taken", "0")
return
}
dumpIntent(data)
if (resultCode == Activity.RESULT_OK) {
try {
val status = data.getBooleanExtra("status", false)
val response = data.getIntExtra("response", 0)
val message = data.getStringExtra("message")
resolve(status.toString(), response.toString(), message.toString())
return
} catch (e: Exception) {
e.printStackTrace()
resolve("01", "Exception occurred in on-boarding " + e.message, "0")
}
}
resolve("01", "No action taken", "0")
}
}
init {
reContext?.addActivityEventListener(mActivityEventListener)
}
@ReactMethod
fun Onboarding(
partnerId: String, partnerKey: String prm: Promise
) {
promise = prm
val currentActivity = currentActivity
val intent = Intent(currentActivity, HostActivity::class.java)
intent.putExtra("pId", partnerId)
intent.putExtra("ApiKey", partnerKey)
try {
currentActivity?.startActivityForResult(intent, CODE)
} catch (e: Exception) {
e.printStackTrace()
resolve("01", "No action taken", "0")
}
}
private fun resolve(
statusCode: String,
response: String,
message: String
) {
if (promise == null) {
return
}
val map = Arguments.createMap()
map.putString("statusCode", statusCode)
map.putString("response", response)
map.putString("message", message)
promise!!.resolve(map)
promise = null
}
private fun LogPrint(key: String?, value: String?) {
if (key == null || value == null) {
return
}
Log.i(key, value)
}
}
主要部分需要添加事件监听器。
init {
reContext?.addActivityEventListener(mActivityEventListener)
}
onActivityResult
并调用mReactInstanceManager.onActivityResult( ... )
(或者任何您称呼它的名称)。或者,您可以从ReactActivity
扩展该 Activity。 - Joshua Pinter