一、拨打电话
权限管理
<uses-permission android:name="android.permission.CALL_PHONE" />
思路
通过Intent设置Action为ACTION_DIAL
或者 ACTION_CALL
,通过intent启动直接拨打电话或者打开拨打电话界面。
示例代码
直接拨打电话
/**
* 拨打电话(直接拨打电话)
* @param phoneNum 电话号码
*/
public void callPhone(String phoneNum){
Intent intent = new Intent(Intent.ACTION_CALL);
Uri data = Uri.parse("tel:" + phoneNum);
intent.setData(data);
startActivity(intent);
}
跳转到拨打电话界面
/**
* 拨打电话(跳转到拨号界面,用户手动点击拨打)
*
* @param phoneNum 电话号码
*/
public void callPhone(String phoneNum) {
Intent intent = new Intent(Intent.ACTION_DIAL);
Uri data = Uri.parse("tel:" + phoneNum);
intent.setData(data);
startActivity(intent);
}
二、蓝牙状态监听
概述
在项目需求中碰到了需要Android设备和蓝牙进行数据交互和操作,需要实时监听蓝牙状态的变化,包括有蓝牙的打开、关闭、连接、断开连接。
考虑到是采用监听的方式,可以设置一个系统全局广播进行监听。
本地广播无法实现蓝牙状态监听
下面是对Android设备中对蓝牙进行状态监听的步骤及代码:
权限
配置文件中添加蓝牙权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
设置广播类
示例代码如下:
class BluetoothMonitorReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var action: String? = intent?.action ?: return
when(action){
BluetoothAdapter.ACTION_STATE_CHANGED ->{
var blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,0)
when(blueState){
BluetoothAdapter.STATE_TURNING_ON ->{
Log.d("TAG","蓝牙设备正在打开")
}
BluetoothAdapter.STATE_ON ->{
Log.d("TAG","蓝牙设备已打开")
}
BluetoothAdapter.STATE_TURNING_OFF ->{
Log.d("TAG","蓝牙设备正在关闭")
}
BluetoothAdapter.STATE_OFF ->{
Log.d("TAG","蓝牙设备已关闭")
}
}
}
BluetoothDevice.ACTION_ACL_CONNECTED -> {
Log.d("TAG","蓝牙设备已连接")
}
BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
Log.d("TAG", "蓝牙设备已断开")
}
}
}
}
Activity中注册代码
class MainActivity : AppCompatActivity() {
private var bluetoothMonitorReceiver:BluetoothMonitorReceiver? =null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
registerBluetoothReceiver()
}
/**
* 注册蓝牙广播
*/
private fun registerBluetoothReceiver() {
if(bluetoothMonitorReceiver == null) {
bluetoothMonitorReceiver = BluetoothMonitorReceiver()
}
var intentFilter = IntentFilter()
//监听打开蓝牙状态
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
//监听蓝牙连接状态
intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
registerReceiver(bluetoothMonitorReceiver, intentFilter)
}
override fun onDestroy() {
unregisterReceiver(bluetoothMonitorReceiver)
super.onDestroy()
}
打开和关闭蓝牙
打开蓝牙
/**
* 打开蓝牙
*/
private fun openBluetooth(){
//申请打开蓝牙弹窗
// var intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
// startActivity(intent)
// 隐式打开蓝牙
var bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.enable()
}
关闭蓝牙
/**
* 关闭蓝牙
*/
private fun closeBluetooth(){
//打开设置中有关蓝牙的页面,不建议使用
// var intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
// startActivity(intent)
// 隐式关闭蓝牙
var bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
bluetoothAdapter.disable()
}
网友评论