android bluetooth api

2024-05-15 23:08
文章标签 android api bluetooth

本文主要是介绍android bluetooth api,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

蓝牙:
1,是目前使用最广泛的无线通讯协议
2.主要针对短距离通讯(10M)
3.常用于连接耳机,鼠标,和移动通读设备等

与蓝牙相关的API
1.BluetoothAdapter
这类的对象代表了本地的蓝牙适配器
2.BluetoothDevice:
代表了一个远程的Bluetooth设备

扫描已配对的蓝牙设备
在AndroidManifest.xml声明蓝牙权限:

<uses-permission 
android:name="android.permission.BLUETOOTH">
</uses-permission>

例子:

package com.example.bluetoothtest.bluetoothtest;import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import java.io.File;
import java.io.IOException;
import java.util.Set;public class MainActivity extends Activity {private static String mFileName = null;private  static  String TAG = "BT_android";MediaRecorder mMediaRecorder;private int record_state;private static int ENABLE_BT = 1;private static int DISABLE_BT = 0;/*tmp file front*/private  String strTempFile = "recaudio_";/*record audio*/private File mRecordAudioFile;private File mRecordAudioPath;private AudioManager  mAudioManager;private Handler mHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what){case 1:Log.d(TAG,"1-----------");Toast.makeText(getApplication(),"1111111",Toast.LENGTH_LONG).show();break;case 0:Log.d(TAG,"0-----------");Toast.makeText(getApplication(),"000000",Toast.LENGTH_LONG).show();break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mMediaRecorder  = new MediaRecorder();final Button startBT = (Button)findViewById(R.id.mybluetooth) ;Button stopBT = (Button)findViewById(R.id.stopBT);Button unpairBT = (Button)findViewById(R.id.unpairDevice);Button startRecord = (Button)findViewById(R.id.startRecord);Button stopRecord = (Button)findViewById(R.id.stopRecord);Button visableBT = (Button)findViewById(R.id.visableBT);final TextView stateBT = (TextView)findViewById(R.id.stateBT);final TextView bounddeviceBT = (TextView)findViewById(R.id.bounddeviceBT);mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);/*mMediaRecorder = new MediaRecorder();*/final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){/*get sdcard's path*/mRecordAudioPath = Environment.getExternalStorageDirectory();}else{Toast.makeText(getApplicationContext(),"no sdcard in box",Toast.LENGTH_LONG);}startBT.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {adapter.enable();Log.d(TAG,"enable BT");//打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)/*    Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)*//*取到扫描到的可见蓝牙设备*/registerReceiver(new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {BluetoothDevice mdevBT = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);Log.e(TAG,mdevBT.getName() + mdevBT.getAddress());}},new IntentFilter(BluetoothDevice.ACTION_FOUND));adapter.startDiscovery();/*得到适配器中已配对过的设备信息*/Set<BluetoothDevice> mPairDevice = adapter.getBondedDevices();if (mPairDevice.size()> 0)for (BluetoothDevice mBtDevice:mPairDevice){bounddeviceBT.append("\nName:" + mBtDevice.getName() + "\tMac:" + mBtDevice.getAddress() + "\n");}Toast.makeText(getApplicationContext(),"scanning-----",Toast.LENGTH_LONG).show();Message mMessage = new Message();mMessage.what = 1;mHandler.sendMessage(mMessage);if (adapter.getState() == adapter.STATE_ON){stateBT.setText("enable BT");}else{stateBT.setText("disable BT");}}});//关闭蓝牙stopBT.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {adapter.disable();Log.d(TAG,"state:"+ adapter.getState());if (adapter.getState() == adapter.STATE_ON){stateBT.setText("enable BT");}else{stateBT.setText("disable BT");}Toast.makeText(getApplicationContext(),"disable BT",Toast.LENGTH_SHORT).show();}});unpairBT.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Log.d(TAG,"unpair BT");if (adapter.getState() == adapter.STATE_ON){stateBT.setText("enable BT");}else{stateBT.setText("disable BT");}Toast.makeText(getApplicationContext(),"unpair BT",Toast.LENGTH_SHORT).show();}});startRecord.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {/* mRecordAudioFile = File.createTempFile(strTempFile,".amr",mRecordAudioPath);*/mRecordAudioFile = new File(mRecordAudioPath.toString(), "zyk.mp3");Toast.makeText(getApplicationContext(), mRecordAudioPath.toString(), Toast.LENGTH_LONG).show();if (!mAudioManager.isBluetoothScoAvailableOffCall()) {Toast.makeText(getApplicationContext(), "BT is not support record", Toast.LENGTH_LONG);return;}/*new a mediarecorder list*//*set the source */mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);/*set the  format*/mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);/*set the encorder*/mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);/*set outpout file's pathc*/mMediaRecorder.setOutputFile(mRecordAudioFile.getAbsolutePath());try {mMediaRecorder.prepare();} catch (IOException e) {e.printStackTrace();}if (!mAudioManager.isBluetoothScoAvailableOffCall()){Log.d(TAG,"system not support BT record");return;}mAudioManager.startBluetoothSco();registerReceiver(new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {record_state = intent.getByteExtra(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED,(byte)-1);if (AudioManager.SCO_AUDIO_STATE_CONNECTED == record_state) {mAudioManager.setBluetoothScoOn(true);mMediaRecorder.start();unregisterReceiver(this);}else {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}},new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));}});stopRecord.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {if (mMediaRecorder != null) {/*   mMediaRecorder.stop();*/mMediaRecorder.release();mMediaRecorder = null;/*  mAudioManager.setBluetoothScoOn(false);mAudioManager.stopBluetoothSco();*/}}});visableBT.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent mvisableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);mvisableBtIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,360);startActivity(mvisableBtIntent);Toast.makeText(getApplicationContext(),"mvisableBtIntent",Toast.LENGTH_LONG).show();}});};}

修改蓝牙设备的可见性,需要以下权限:

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN">
</uses-permission>

如下将蓝牙适配器可见的时间调整为70s

Intent mvisableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);   mvisableBtIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,70);
startActivity(mvisableBtIntent);   Toast.makeText(getApplicationContext(),"mvisableBtIntent",Toast.LENGTH_LONG).show();
``

这篇关于android bluetooth api的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/993183

相关文章

Java调用DeepSeek API的8个高频坑与解决方法

《Java调用DeepSeekAPI的8个高频坑与解决方法》现在大模型开发特别火,DeepSeek因为中文理解好、反应快、还便宜,不少Java开发者都用它,本文整理了最常踩的8个坑,希望对... 目录引言一、坑 1:Token 过期未处理,鉴权异常引发服务中断问题本质典型错误代码解决方案:实现 Token

Android使用java实现网络连通性检查详解

《Android使用java实现网络连通性检查详解》这篇文章主要为大家详细介绍了Android使用java实现网络连通性检查的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录NetCheck.Java(可直接拷贝)使用示例(Activity/Fragment 内)权限要求

2025最新版Android Studio安装及组件配置教程(SDK、JDK、Gradle)

《2025最新版AndroidStudio安装及组件配置教程(SDK、JDK、Gradle)》:本文主要介绍2025最新版AndroidStudio安装及组件配置(SDK、JDK、Gradle... 目录原生 android 简介Android Studio必备组件一、Android Studio安装二、A

使用Go调用第三方API的方法详解

《使用Go调用第三方API的方法详解》在现代应用开发中,调用第三方API是非常常见的场景,比如获取天气预报、翻译文本、发送短信等,Go作为一门高效并发的编程语言,拥有强大的标准库和丰富的第三方库,可以... 目录引言一、准备工作二、案例1:调用天气查询 API1. 注册并获取 API Key2. 代码实现3

Android实现图片浏览功能的示例详解(附带源码)

《Android实现图片浏览功能的示例详解(附带源码)》在许多应用中,都需要展示图片并支持用户进行浏览,本文主要为大家介绍了如何通过Android实现图片浏览功能,感兴趣的小伙伴可以跟随小编一起学习一... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

在Android中使用WebView在线查看PDF文件的方法示例

《在Android中使用WebView在线查看PDF文件的方法示例》在Android应用开发中,有时我们需要在客户端展示PDF文件,以便用户可以阅读或交互,:本文主要介绍在Android中使用We... 目录简介:1. WebView组件介绍2. 在androidManifest.XML中添加Interne

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

Android协程高级用法大全

《Android协程高级用法大全》这篇文章给大家介绍Android协程高级用法大全,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友跟随小编一起学习吧... 目录1️⃣ 协程作用域(CoroutineScope)与生命周期绑定Activity/Fragment 中手

Go语言使用net/http构建一个RESTful API的示例代码

《Go语言使用net/http构建一个RESTfulAPI的示例代码》Go的标准库net/http提供了构建Web服务所需的强大功能,虽然众多第三方框架(如Gin、Echo)已经封装了很多功能,但... 目录引言一、什么是 RESTful API?二、实战目标:用户信息管理 API三、代码实现1. 用户数据

Python用Flask封装API及调用详解

《Python用Flask封装API及调用详解》本文介绍Flask的优势(轻量、灵活、易扩展),对比GET/POST表单/JSON请求方式,涵盖错误处理、开发建议及生产环境部署注意事项... 目录一、Flask的优势一、基础设置二、GET请求方式服务端代码客户端调用三、POST表单方式服务端代码客户端调用四