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

相关文章

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

Android里面的Service种类以及启动方式

《Android里面的Service种类以及启动方式》Android中的Service分为前台服务和后台服务,前台服务需要亮身份牌并显示通知,后台服务则有启动方式选择,包括startService和b... 目录一句话总结:一、Service 的两种类型:1. 前台服务(必须亮身份牌)2. 后台服务(偷偷干

浅析如何使用Swagger生成带权限控制的API文档

《浅析如何使用Swagger生成带权限控制的API文档》当涉及到权限控制时,如何生成既安全又详细的API文档就成了一个关键问题,所以这篇文章小编就来和大家好好聊聊如何用Swagger来生成带有... 目录准备工作配置 Swagger权限控制给 API 加上权限注解查看文档注意事项在咱们的开发工作里,API

一分钟带你上手Python调用DeepSeek的API

《一分钟带你上手Python调用DeepSeek的API》最近DeepSeek非常火,作为一枚对前言技术非常关注的程序员来说,自然都想对接DeepSeek的API来体验一把,下面小编就来为大家介绍一下... 目录前言免费体验API-Key申请首次调用API基本概念最小单元推理模型智能体自定义界面总结前言最

JAVA调用Deepseek的api完成基本对话简单代码示例

《JAVA调用Deepseek的api完成基本对话简单代码示例》:本文主要介绍JAVA调用Deepseek的api完成基本对话的相关资料,文中详细讲解了如何获取DeepSeekAPI密钥、添加H... 获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。添加HTTP客户端依赖使用Jav

C#使用DeepSeek API实现自然语言处理,文本分类和情感分析

《C#使用DeepSeekAPI实现自然语言处理,文本分类和情感分析》在C#中使用DeepSeekAPI可以实现多种功能,例如自然语言处理、文本分类、情感分析等,本文主要为大家介绍了具体实现步骤,... 目录准备工作文本生成文本分类问答系统代码生成翻译功能文本摘要文本校对图像描述生成总结在C#中使用Deep

Android kotlin语言实现删除文件的解决方案

《Androidkotlin语言实现删除文件的解决方案》:本文主要介绍Androidkotlin语言实现删除文件的解决方案,在项目开发过程中,尤其是需要跨平台协作的项目,那么删除用户指定的文件的... 目录一、前言二、适用环境三、模板内容1.权限申请2.Activity中的模板一、前言在项目开发过程中,尤

5分钟获取deepseek api并搭建简易问答应用

《5分钟获取deepseekapi并搭建简易问答应用》本文主要介绍了5分钟获取deepseekapi并搭建简易问答应用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需... 目录1、获取api2、获取base_url和chat_model3、配置模型参数方法一:终端中临时将加

使用DeepSeek API 结合VSCode提升开发效率

《使用DeepSeekAPI结合VSCode提升开发效率》:本文主要介绍DeepSeekAPI与VisualStudioCode(VSCode)结合使用,以提升软件开发效率,具有一定的参考价值... 目录引言准备工作安装必要的 VSCode 扩展配置 DeepSeek API1. 创建 API 请求文件2.

使用SpringBoot创建一个RESTful API的详细步骤

《使用SpringBoot创建一个RESTfulAPI的详细步骤》使用Java的SpringBoot创建RESTfulAPI可以满足多种开发场景,它提供了快速开发、易于配置、可扩展、可维护的优点,尤... 目录一、创建 Spring Boot 项目二、创建控制器类(Controller Class)三、运行