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);
}
相关推荐
脑袋大大的5 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
速易达网络6 小时前
RuoYi、Vue CLI 和 uni-app 结合构建跨端全家桶方案
javascript·vue.js·低代码
耶啵奶膘6 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
JoJo_Way6 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
视频砖家7 小时前
移动端Html5播放器按钮变小的问题解决方法
前端·javascript·viewport功能
雨白9 小时前
Jetpack系列(二):Lifecycle与LiveData结合,打造响应式UI
android·android jetpack
GISer_Jing10 小时前
Monorepo+Pnpm+Turborepo
前端·javascript·ecmascript
天涯学馆10 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试
kk爱闹10 小时前
【挑战14天学完python和pytorch】- day01
android·pytorch·python