uniapp Native.js 调用安卓arr原生service

有问题,文中的内容不正确

最近搞了个uni小项目,一个定制的小平板,带一个nfc设备,厂家只给了一套安卓原生demo,头一次玩原生安卓,废了好半天劲打出来arr包,想镶进uniapp里,网上查了好久,都是错的,要么无法运行,要么运行了没反应,要么编译都过不去。。。官网给的示例更是没有示例,主打一个用法全靠猜。。。

服务

厂家给了个NfcService 里面是继承自标准android.app.Service另一部分是个androidx.appcompat.app.AppCompatActivity页面,里面启动,调用的NfcService

java部分NfcService核心代码

kt 复制代码
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的一个页面

js 复制代码
//开启服务(无回值启动)
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);
}
相关推荐
red润2 分钟前
封装hook,复刻掘金社区,暗黑白天主题切换功能
前端·javascript·vue.js
葬送的代码人生20 分钟前
React组件化哲学:如何优雅地"变秃也变强"
前端·javascript·react.js
雨白25 分钟前
深入理解广播机制 (BroadcastReceiver)
android
Bl_a_ck25 分钟前
【JS进阶】ES6 实现继承的方式
开发语言·前端·javascript
咪库咪库咪31 分钟前
js的浅拷贝与深拷贝
javascript
幸福的猪在江湖32 分钟前
第一章:变量筑基 - 内力根基修炼法
javascript
Ryan今天学习了吗32 分钟前
💥不说废话,带你使用原生 JS + HTML 实现超丝滑拖拽排序效果
javascript·html
Momoly0833 分钟前
vue3+el-table 利用插槽自定义数据样式
前端·javascript·vue.js
多啦C梦a34 分钟前
从 React 初体验到数据驱动的界面开发:一步步解析 Todo List 组件
javascript·react.js
Spider_Man35 分钟前
“AI查用户”也能这么简单?手把手带你用Node.js+前端玩转DeepSeek!
javascript·人工智能·node.js