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

相关文章

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

Android实现在线预览office文档的示例详解

《Android实现在线预览office文档的示例详解》在移动端展示在线Office文档(如Word、Excel、PPT)是一项常见需求,这篇文章为大家重点介绍了两种方案的实现方法,希望对大家有一定的... 目录一、项目概述二、相关技术知识三、实现思路3.1 方案一:WebView + Office Onl

Android实现两台手机屏幕共享和远程控制功能

《Android实现两台手机屏幕共享和远程控制功能》在远程协助、在线教学、技术支持等多种场景下,实时获得另一部移动设备的屏幕画面,并对其进行操作,具有极高的应用价值,本项目旨在实现两台Android手... 目录一、项目概述二、相关知识2.1 MediaProjection API2.2 Socket 网络

Android实现悬浮按钮功能

《Android实现悬浮按钮功能》在很多场景中,我们希望在应用或系统任意界面上都能看到一个小的“悬浮按钮”(FloatingButton),用来快速启动工具、展示未读信息或快捷操作,所以本文给大家介绍... 目录一、项目概述二、相关技术知识三、实现思路四、整合代码4.1 Java 代码(MainActivi

Android Mainline基础简介

《AndroidMainline基础简介》AndroidMainline是通过模块化更新Android核心组件的框架,可能提高安全性,本文给大家介绍AndroidMainline基础简介,感兴趣的朋... 目录关键要点什么是 android Mainline?Android Mainline 的工作原理关键

如何解决idea的Module:‘:app‘platform‘android-32‘not found.问题

《如何解决idea的Module:‘:app‘platform‘android-32‘notfound.问题》:本文主要介绍如何解决idea的Module:‘:app‘platform‘andr... 目录idea的Module:‘:app‘pwww.chinasem.cnlatform‘android-32

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

Android Studio 配置国内镜像源的实现步骤

《AndroidStudio配置国内镜像源的实现步骤》本文主要介绍了AndroidStudio配置国内镜像源的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、修改 hosts,解决 SDK 下载失败的问题二、修改 gradle 地址,解决 gradle

在Android平台上实现消息推送功能

《在Android平台上实现消息推送功能》随着移动互联网应用的飞速发展,消息推送已成为移动应用中不可或缺的功能,在Android平台上,实现消息推送涉及到服务端的消息发送、客户端的消息接收、通知渠道(... 目录一、项目概述二、相关知识介绍2.1 消息推送的基本原理2.2 Firebase Cloud Me