uni-app 原生插件如何使用广播的方式实现传值
uni-app 原生插件如何使用广播的方式实现传值
代码示例
var globalEvent = uni.requireNativePlugin('globalEvent');  
globalEvent.addEventListener('baScanViewEvent', function(e) {  
    console.log('baScanViewEvent' + JSON.stringify(e));  
});
这种注册事件的方式,插件可以通过这个方式传值到前端
有没有大佬知道怎么实现啊,,,,头皮都抠破啦
被折磨了一波,总算解决了
js代码
mounted() {
let that = this
        plus.globalEvent.addEventListener('callBackText', function(e) {  
            // uni.showModal({  
            //  title: 'fcm notify',  
            //  content: "fcmNotify收到:" + JSON.stringify(e)  
            // });  
            if(e.code == 0){  
                let text = "";  
                text += "-----" + that.$DataUtil.formatNow("Y-M-D h:m:s") + "-----" + "\n";  
                text += JSON.stringify(e.data);  
                that.zhi = text;  
            }  
        });  
    },
调用代码
openFun() {
let that = this
plugin.openAudio(function(res) {
console.log(“initDevice”)
console.log(res)
uni.showModal({
title: JSON.stringify(res)
})
// if (res.code == 0) {
//  that.zhi += “\n” + “-----” + that.$DataUtil.formatNow(“Y-M-D h:m:s”) + “-----” + “\n”;
//  that.zhi += res.data;
// }
});
},
android Kotlin 代码
@UniJSMethod(uiThread = true)
fun openAudio(jsCallback: UniJSCallback?) {
val result = JSONObject()
if (!isRecording) {
val ret = initMicrophone()
if (!ret) {
UniLogUtils.e(TAG, “Failed to initialize microphone”)
if (jsCallback != null) {
result.put(“code”, -1)
result.put(“data”, null)
result.put(“msg”, “Failed to initialize microphone”)
jsCallback.invoke(result)
}
return
}
UniLogUtils.i(TAG, “state: ${audioRecord?.state}”)
audioRecord!!.startRecording()
isRecording = true
model.reset()
lastText = “”
idx = 0
recordingThread = thread(true) {
processSamples()
}
//            mUniSDKInstance.runOnUiThread {
//                    processSamples()
//            }
UniLogUtils.i(TAG, “Started recording”)
if (jsCallback != null) {
result.put(“code”, 0)
result.put(“data”, null)
result.put(“msg”, “开启语音监听成功”)
jsCallback.invoke(result)
}
} else {
isRecording = false
audioRecord!!.stop()
audioRecord!!.release()
audioRecord = null
UniLogUtils.i(TAG, “Stopped recording”)
if (jsCallback != null) {
result.put(“code”, 0)
result.put(“data”, null)
result.put(“msg”, “停止语音监听成功”)
jsCallback.invoke(result)
}
}  
}
实现循环传参
private fun processSamples() {
UniLogUtils.i(TAG, “processing samples”)
val resultData = JSONObject()
val interval = 0.1 // i.e., 100 ms
val bufferSize = (interval * sampleRateInHz).toInt() // in samples
val buffer = ShortArray(bufferSize)
while (isRecording) {  
    val ret = audioRecord?.read(buffer, 0, buffer.size)  
    if (ret != null && ret > 0) {  
        val samples = FloatArray(ret) { buffer[it] / 32768.0f }  
        model.acceptSamples(samples)  
        while (model.isReady()) {  
            model.decode()  
        }  
            UniLogUtils.i(TAG, "Handler is running: ${handler.looper.isCurrentThread}")  
                val isEndpoint = model.isEndpoint()  
                val text = model.text  
                if (text.isNotBlank()) {  
                    if (lastText.isBlank()) {  
                        resultData.put("text", "${idx}: ${text}");  
                        resultData.put("isEndpoint", isEndpoint);  
                    } else {  
                        resultData.put("text", "${lastText}\n${idx}: ${text}");  
                        resultData.put("isEndpoint", isEndpoint);  
                    }  
                }  
                if (isEndpoint) {  
                    model.reset()  
//                        if (text.isNotBlank()) {
//                            lastText = “${lastText}\n${idx}: ${text}”
//                            idx += 1
//                        }
}
sendEventToJS(“callBackText”,0,resultData,“获取语音文字成功”);
}
}
}
这样就能把android识别到的语音转成文字实时发送到uniapp去使用了
希望下一个兄弟不会被折磨把,恶心人,
我特么头皮抠烂
更多关于uni-app 原生插件如何使用广播的方式实现传值的实战教程也可以访问 https://www.itying.com/category-93-b0.html
学习了
在 uni-app 中,原生插件通过广播的方式实现传值通常涉及两个主要部分:原生插件的接收与发送广播,以及 uni-app 前端代码触发或接收这些广播。以下是一个简要的实现示例,分别展示了如何在 Android 和 iOS 平台上使用广播。
Android 平台
1. 原生插件接收广播
在 Android 原生插件中,你需要创建一个 BroadcastReceiver 来接收广播。例如,创建一个名为 MyBroadcastReceiver 的类:
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String value = intent.getStringExtra("key");
        // 处理接收到的值
    }
}
然后在插件的 Manifest.xml 中注册这个 BroadcastReceiver:
<receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
        <action android:name="com.example.MY_ACTION" />
    </intent-filter>
</receiver>
2. 发送广播
在 uni-app 的前端代码中,通过调用原生插件的方法来发送广播:
// 假设你已经通过 uni-app 引入了原生插件,并且插件 ID 为 'myPlugin'
uni.requireNativePlugin('myPlugin').sendBroadcast({
    action: 'com.example.MY_ACTION',
    extras: {
        key: 'value'
    },
    success: function (res) {
        console.log('Broadcast sent successfully');
    },
    fail: function (err) {
        console.error('Failed to send broadcast', err);
    }
});
iOS 平台
1. 原生插件接收广播
在 iOS 中,广播机制通常通过 NotificationCenter 实现。在插件的 Objective-C 或 Swift 代码中,添加通知监听:
// Objective-C 示例
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(handleNotification:)
                                             name:@"com.example.MyNotification"
                                           object:nil];
- (void)handleNotification:(NSNotification *)notification {
    NSString *value = [notification.userInfo objectForKey:@"key"];
    // 处理接收到的值
}
2. 发送广播
在 uni-app 的前端代码中,通过调用原生插件的方法来发送通知:
// 假设你已经通过 uni-app 引入了原生插件,并且插件 ID 为 'myPlugin'
uni.requireNativePlugin('myPlugin').postNotification({
    name: 'com.example.MyNotification',
    userInfo: {
        key: 'value'
    },
    success: function (res) {
        console.log('Notification posted successfully');
    },
    fail: function (err) {
        console.error('Failed to post notification', err);
    }
});
请注意,以上代码仅为示例,实际实现中可能需要根据具体需求调整,并确保在适当的生命周期方法中注册和注销广播接收器或通知监听器,以避免内存泄漏等问题。
        
      
                    
                  
                    
