您现在的位置是:网站首页> 小程序设计
Native API经典实用例子
- 小程序设计
- 2024-08-21
- 848人已阅读
uniapp快速回顾
安卓Native.js蓝牙连接票据打印机完整代码已测试修改
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/pr.js"></script>
</head>
<body>
<p><input id="bt1" type="button" value="搜索设备" onclick="searchDevices('a')"></p>
</button>
</div>
<div>
未配对蓝牙设备
<ul id="list1">
</ul>
</div>
<div>
已配对蓝牙设备
<ul id="list2">
</ul>
</div>
</body>
</html>
下面是js文件
//address=""搜索蓝牙//address=设备mac地址,自动配对给出mac地址的设备
function searchDevices(address) {
//注册类
var main = plus.android.runtimeMainActivity();
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
var BAdapter = BluetoothAdapter.getDefaultAdapter();
console.log("开始搜索设备");
var filter = new IntentFilter();
var bdevice = new BluetoothDevice();
var on = null;
var un = null;
var vlist1 = document.getElementById('list1'); //注册容器用来显示未配对设备
vlist1.innerHTML = ''; //清空容器
var vlist2 = document.getElementById('list2'); //注册容器用来显示未配对设备
vlist2.innerHTML = ''; //清空容器
var button1 = document.getElementById('bt1');
button1.disabled=true;
button1.value='正在搜索请稍候';
BAdapter.startDiscovery(); //开启搜索
var receiver;
receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
onReceive: function(context, intent) { //实现onReceiver回调函数
plus.android.importClass(intent); //通过intent实例引入intent类,方便以后的‘.’操作
console.log(intent.getAction()); //获取action
if(intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED"){
main.unregisterReceiver(receiver);//取消监听
button1.disabled=false;
button1.value='搜索设备';
console.log("搜索结束")
}else{
BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//判断是否配对
if (BleDevice.getBondState() == bdevice.BOND_NONE) {
console.log("未配对蓝牙设备:" + BleDevice.getName() + ' ' + BleDevice.getAddress());
//参数如果跟取得的mac地址一样就配对
if (address == BleDevice.getAddress()) {
if (BleDevice.createBond()) { //配对命令.createBond()
console.log("配对成功");
var li2 = document.createElement('li'); //注册
li2.setAttribute('id', BleDevice.getAddress()); //打印机mac地址
li2.setAttribute('onclick', 'print(id)'); //注册click点击列表进行打印
li2.innerText = BleDevice.getName();
vlist2.appendChild(li2);
}
} else {
if(BleDevice.getName() != on ){ //判断防止重复添加
var li1 = document.createElement('li'); //注册
li1.setAttribute('id', BleDevice.getAddress()); //打印机mac地址
li1.setAttribute('onclick', 'searchDevices(id)'); //注册click点击列表进行配对
on = BleDevice.getName();
li1.innerText = on;
vlist1.appendChild(li1);
}
}
} else {
if(BleDevice.getName() != un ){ //判断防止重复添加
console.log("已配对蓝牙设备:" + BleDevice.getName() + ' ' + BleDevice.getAddress());
var li2 = document.createElement('li'); //注册
li2.setAttribute('id', BleDevice.getAddress()); //打印机mac地址
li2.setAttribute('onclick', 'print(id)'); //注册click点击列表进行打印
un = BleDevice.getName();
li2.innerText = un;
vlist2.appendChild(li2);}
}}
}
});
filter.addAction(bdevice.ACTION_FOUND);
filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BAdapter.ACTION_STATE_CHANGED);
main.registerReceiver(receiver, filter); //注册监听
}
var device = null,
BAdapter = null,
BluetoothAdapter = null,
uuid = null,
main = null,
bluetoothSocket = null;
function print(mac_address) {
if (!mac_address) {
mui.toast('请选择蓝牙打印机');
return;
}
main = plus.android.runtimeMainActivity();
BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
UUID = plus.android.importClass("java.util.UUID");
uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BAdapter = BluetoothAdapter.getDefaultAdapter();
device = BAdapter.getRemoteDevice(mac_address);
plus.android.importClass(device);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
plus.android.importClass(bluetoothSocket);
if (!bluetoothSocket.isConnected()) {
console.log('检测到设备未连接,尝试连接....');
bluetoothSocket.connect();
}
console.log('设备已连接');
if (bluetoothSocket.isConnected()) {
var outputStream = bluetoothSocket.getOutputStream();
plus.android.importClass(outputStream);
var string = "打印测试\r\n";
var bytes = plus.android.invoke(string, 'getBytes', 'gbk');
outputStream.write(bytes);
outputStream.flush();
device = null //这里关键
bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误
}
}
Android调用系统通讯录控件,native.js实现监听startActivityForResult后返回结果
var REQUESTCODE = 1000;
main = plus.android.runtimeMainActivity();
var Intent = plus.android.importClass('android.content.Intent');
var ContactsContract = plus.android.importClass('android.provider.ContactsContract');
var intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
main.onActivityResult = function(requestCode, resultCode, data) {
if (REQUESTCODE == requestCode) {
var phoneNumber = null;
var resultString = "";
var context = main;
plus.android.importClass(data);
var contactData = data.getData();
var resolver = context.getContentResolver();
plus.android.importClass(resolver);
var cursor = resolver.query(contactData, null, null, null, null);
plus.android.importClass(cursor);
cursor.moveToFirst();
var s_ret;
var givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
s_ret = givenName;
var contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
var pCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
null, null);
while (pCursor.moveToNext()) {
phoneNumber = pCursor.getString( pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
s_ret += '\n' + phoneNumber;
}
alert(s_ret);
cursor.close();
pCursor.close();
}
};
main.startActivityForResult(intent, REQUESTCODE);
以监听手机飞行模式开关为例说明如何使用Native.js进行BroadcastReceiver广播
var receiver;
main = plus.android.runtimeMainActivity(); //获取activity
receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
onReceive: function(context, intent) { //实现onReceiver回调函数
plus.android.importClass(intent);
console.log(intent.getAction());
result.textContent += '\nAction :' + intent.getAction();
main.unregisterReceiver(receiver);
}
});
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
var Intent = plus.android.importClass('android.content.Intent');
var filter = new IntentFilter();
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); //监听飞行模式
main.registerReceiver(receiver, filter); //注册监听
使用NJS控制Android通知栏,不用个推实现本地消息推送
var NotifyID = 1;
var Context = plus.android.importClass("android.content.Context");
var main = plus.android.runtimeMainActivity();
var Noti = plus.android.importClass("android.app.Notification");
var NotificationManager = plus.android.importClass("android.app.NotificationManager");
var nm = main.getSystemService(Context.NOTIFICATION_SERVICE)
var Notification = plus.android.importClass("android.app.Notification");
var mNotification = new Notification.Builder(main);
mNotification.setOngoing(true);
mNotification.setContentTitle("Hbuilder")
mNotification.setContentText("MUI & 5+ 大好!")
mNotification.setSmallIcon(17301620)
mNotification.setTicker("PadInfo")
mNotification.setNumber(10)
var mNb = mNotification.build()
nm.notify(NotifyID , mNb);
调用Native.js,如何启动一个service?
var main = plus.android.runtimeMainActivity();
var Intent = plus.android.importClass('android.content.Intent');
var intent = new Intent();
intent.setClassName(main, "io.dcloud.test.MyService");
main.startService(intent);
Android监听电话呼入呼出
(function($) {
var receiver, main, context, TelephonyManager;
$.plusReady(function() {
context = plus.android.importClass('android.content.Context'); //上下文
TelephonyManager = plus.android.importClass('android.telephony.TelephonyManager'); //通话管理
main = plus.android.runtimeMainActivity(); //获取activity
receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
onReceive: doReceive //实现onReceiver回调函数
});
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
var Intent = plus.android.importClass('android.content.Intent');
var filter = new IntentFilter();
//filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); //监听飞行模式
filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); //监听电话状态
main.registerReceiver(receiver, filter); //注册监听
});
function doReceive(context, intent) {
plus.android.importClass(intent);
var phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER),
telephony = context.getSystemService(context.TELEPHONY_SERVICE),
state = telephony.getCallState();
switch(state) {
case TelephonyManager.CALL_STATE_RINGING:
console.log("[Broadcast]等待接电话=" + phoneNumber);
break;
case TelephonyManager.CALL_STATE_IDLE:
console.log("[Broadcast]电话挂断=" + phoneNumber);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
console.log("[Broadcast]通话中=" + phoneNumber);
break;
}
console.log(intent.getAction());
}
}(mui));
上一篇:uniapp快速回顾
下一篇:Flex布局快速总结