最近搞了个uni小项目,一个定制的小平板,带一个nfc设备,厂家只给了一套安卓原生demo,头一次玩原生安卓,废了好半天劲打出来arr包,想镶进uniapp里,网上查了好久,都是错的,要么无法运行,要么运行了没反应,要么编译都过不去。。。官网给的示例更是没有示例,主打一个用法全靠猜。。。
服务
厂家给了个NfcService
里面是继承自标准android.app.Service
另一部分是个androidx.appcompat.app.AppCompatActivity
页面,里面启动,调用的NfcService
java部分NfcService
核心代码
private val connection = object : ServiceConnection {
override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
Log.e(TAG, "onServiceConnected: ")
nfcBinder = p1 as NfcService.MyBinder
nfcBinder?.openPort(model)
}
override fun onServiceDisconnected(p0: ComponentName?) {
Log.e(TAG, "onServiceDisconnected: ")
nfcBinder = null
}
}
override fun onCreate(savedInstanceState: Bundle?) {
//无关代码太多,就不粘了
//绑定服务
bindService(Intent(this, NfcService::class.java), connection, Context.BIND_AUTO_CREATE)
//一定条件后,解绑服务
unbindService(connection)
}
从没接触过安卓原生,一下子就麻了,不知道在uni那边怎么用,找了半天找到了这个
uniapp的一个页面
//开启服务(无回值启动)
startAppService(){
const mainActivity = plus.android.runtimeMainActivity();
const Context = plus.android.importClass('android.content.Context');
const Intent = plus.android.importClass('android.content.Intent');
const intent = new Intent();
intent.setClassName(mainActivity, 'com.rt.lib_nfc.NfcService');
const Bundle = plus.android.importClass('android.os.Bundle');
var bundle = new Bundle();
intent.putExtras(bundle);
mainActivity.startForegroundService(intent)
},
//绑定服务(有回值启动)
bindAppService(){
const main = plus.android.runtimeMainActivity();
const Context = plus.android.importClass('android.content.Context');
const Service = plus.android.importClass('android.app.Service');
const Intent = plus.android.importClass('android.content.Intent');
let serviceConnectionFunc = {
onServiceConnected: function(name, service) {
console.log("服务已连接", name, service);
//service.openPort('READ');
this.nfcService = service;
},
onServiceDisconnected: function(name) {
console.log("服务已断开", name);
this.nfcService = null;
}
};
let serviceConnection = plus.android.implements('android.content.ServiceConnection', serviceConnectionFunc);
const intent = new Intent();
intent.setClassName(main, 'com.rt.lib_nfc.NfcService');
main.bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
},
//最终使用
testService(){
let res = this.nfcService?.openPort('get');
console.log('res ->', res);
}