蓝牙音箱BluetoothA2dp
package myapplication.com.mybuletooch; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast; import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; public class MainActivity extends AppCompatActivity {
BluetoothAdapter adapter;
ArrayList<String> datas = new ArrayList<String>();
ListView listv;
ArrayAdapter<String> ad;
BluetoothDevice remoteD;
List<BluetoothDevice> mBluetoothDevices; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initView();
} private void initView() {
listv = (ListView) findViewById(R.id.listView);
listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String bl = datas.get(position);
//使用"-"分割字符串
String[] values = bl.split("-");
// connect(mBluetoothDevices.get(position).getAddress(), position);
// connect(values[values.length - 1]);
// connect(mBluetoothDevices.get(position));
// Toast.makeText(MainActivity.this, mBluetoothDevices.get(position).getAddress(), Toast.LENGTH_SHORT).show();
}
});
ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, datas);
listv.setAdapter(ad); } //初始化
private void init() {
mBluetoothDevices = new ArrayList<>();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
//动态注册广播接收器
this.registerReceiver(receiver, filter); } class A extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
//获取扫描到的设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBluetoothDevices.add(device); String name = device.getName();
String address = device.getAddress();
System.out.println("--扫到的设备:" + name + ":" + address);
//数据变化了 datas.add(name + "-" + address);
//刷新列表
ad.notifyDataSetChanged();
}
}
} private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 获取查找到的蓝牙设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getName());
// 如果查找到的设备符合要连接的设备,处理
String name = device.getName();
String address = device.getAddress();
System.out.println("--扫到的设备:" + name + ":" + address);
//数据变化了
datas.add(name + "-" + address);
//刷新列表
ad.notifyDataSetChanged();
// 搜索蓝牙设备的过程占用资源比较多,一旦找到需要连接的设备后需要及时关闭搜索
adapter.cancelDiscovery();
// 获取蓝牙设备的连接状态
int connectState = device.getBondState();
remoteD = device;
switch (connectState) {
// 未配对
case BluetoothDevice.BOND_NONE:
Log.i("走配对", "onReceive: " + "走配对方法了");
// 配对
try {
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
break;
// 已配对
case BluetoothDevice.BOND_BONDED:
// 连接
// new ConnectThread(device).start();
adapter.getProfileProxy(getApplicationContext(), mA2dpProfileListener, BluetoothProfile.A2DP);
adapter.getProfileProxy(getApplicationContext(), mHeadsetProfileListener, BluetoothProfile.HEADSET);
Log.i("走连接方法啦", "onReceive: ");
break;
}
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
// 状态改变的广播
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int connectState = device.getBondState();
remoteD = device;
switch (connectState) {
case BluetoothDevice.BOND_NONE:
break;
case BluetoothDevice.BOND_BONDING:
break;
case BluetoothDevice.BOND_BONDED:
// 连接
Log.i("走连接方法啦", "onReceive: ");
// connect(device);
// new ConnectThread(device).start();
break;
} }
}
};
BluetoothA2dp mBluetoothA2dp;
private BluetoothProfile.ServiceListener mA2dpProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothA2dp = (BluetoothA2dp) proxy;
try {
ClsUtils.connect(mBluetoothA2dp.getClass(), mBluetoothA2dp, remoteD);
} catch (Exception e) {
adapter.closeProfileProxy(BluetoothProfile.A2DP, mBluetoothA2dp);
e.printStackTrace();
}
}
} public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothA2dp = null;
}
}
}; /**
* @Fields mHeadsetProfileListener : BluetoothHeadset服务监听器
*/
BluetoothHeadset mBluetoothHeadset;
private BluetoothProfile.ServiceListener mHeadsetProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = (BluetoothHeadset) proxy;
try { ClsUtils.connect(mBluetoothHeadset.getClass(), mBluetoothHeadset, remoteD);
} catch (Exception e) {
adapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
e.printStackTrace();
}
}
} public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null;
}
}
}; }
ClsUtils.java
package myapplication.com.mybuletooch; import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.util.Log; import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List; @SuppressLint("NewApi") public class ClsUtils {
public ClsUtils() {
// TODO Auto-generated constructor stub
} /**
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
static public boolean createBond(Class<? extends BluetoothDevice> btClass,
BluetoothDevice btDevice) throws Exception { Method createBondMethod = btClass.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
} /**
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
static public boolean removeBond(Class<? extends BluetoothDevice> btClass,
BluetoothDevice btDevice) throws Exception {
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
} static public boolean setPin(Class btClass, BluetoothDevice btDevice,
byte[] str) throws Exception {
try {
Method removeBondMethod = btClass.getDeclaredMethod("setPin",new Class[] { byte[].class });
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,str);
return returnValue.booleanValue();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false; } static public boolean cancelPairingUserInput(Class<?> btClass,
BluetoothDevice device) throws Exception {
Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
cancelBondProcess(btClass, device);
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
return returnValue.booleanValue();
} static public boolean cancelBondProcess(Class<?> btClass,
BluetoothDevice device) throws Exception {
Method createBondMethod = btClass.getMethod("cancelBondProcess");
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
return returnValue.booleanValue();
} /**
*
* @param clsShow
*/
static public void printAllInform(Class<?> clsShow) {
try {
Method[] hideMethod = clsShow.getMethods();
int i = 0;
for (; i < hideMethod.length; i++) {
Log.e("method name", hideMethod[i].getName() + ";and the i is:"
+ i);
}
Field[] allFields = clsShow.getFields();
for (i = 0; i < allFields.length; i++) {
Log.e("Field name", allFields[i].getName());
}
} catch (SecurityException e) {
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
} catch (IllegalArgumentException e) {
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} static public boolean pair(String strAddr, byte[] strPsw) {
boolean result = false;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothAdapter.cancelDiscovery(); if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
} BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr); if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
try {
Log.d("mylog", "NOT BOND_BONDED");
boolean flag1 = ClsUtils.setPin(device.getClass(), device,
strPsw);
boolean flag2 = ClsUtils.createBond(device.getClass(), device);
// remoteDevice = device; result = true; } catch (Exception e) {
// TODO Auto-generated catch block Log.d("mylog", "setPiN failed!");
e.printStackTrace();
} // } else {
Log.d("mylog", "HAS BOND_BONDED");
try {
ClsUtils.removeBond(device.getClass(), device);
// ClsUtils.createBond(device.getClass(), device);
boolean flag1 = ClsUtils.setPin(device.getClass(), device,
strPsw);
boolean flag2 = ClsUtils.createBond(device.getClass(), device); result = true; } catch (Exception e) {
// TODO Auto-generated catch block
Log.d("mylog", "setPiN failed!");
e.printStackTrace();
}
}
return result;
} //A2DP �� HeadSet
public static boolean connect(Class btClass,BluetoothProfile proxy,BluetoothDevice btDevice) throws Exception {
Method connectMethod = btClass.getDeclaredMethod("connect", BluetoothDevice.class);
connectMethod.setAccessible(true);
Boolean returnValue = (Boolean) connectMethod.invoke(proxy,btDevice);
return returnValue.booleanValue();
} public static boolean disconnect(Class btClass,BluetoothProfile proxy,BluetoothDevice btDevice) throws Exception {
Method disconnectMethod = btClass.getDeclaredMethod("disconnect", BluetoothDevice.class);
disconnectMethod.setAccessible(true);
Boolean returnValue = (Boolean) disconnectMethod.invoke(proxy,btDevice);
return returnValue.booleanValue();
} public static void setDiscoverableTimeout(int timeout) {
BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();
try {
Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
setDiscoverableTimeout.setAccessible(true);
Method setScanMode =BluetoothAdapter.class.getMethod("setScanMode", int.class,int.class);
setScanMode.setAccessible(true);
setDiscoverableTimeout.invoke(adapter, timeout);
setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE,timeout);
} catch (Exception e) {
e.printStackTrace();
}
} public static void closeDiscoverableTimeout() {
BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();
try {
Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
setDiscoverableTimeout.setAccessible(true);
Method setScanMode =BluetoothAdapter.class.getMethod("setScanMode", int.class,int.class);
setScanMode.setAccessible(true); setDiscoverableTimeout.invoke(adapter, 1);
setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE,1);
} catch (Exception e) {
e.printStackTrace();
}
}
// CheckConnectingListener
// public static void getCurrentConnectingDevice(Context mcContext,BluetoothAdapter bluetoothAdapter,final CheckConnectingListener listener){
// int a2dp = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
// int headset = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
// int health = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);
// int flag = -1;
// if (a2dp == BluetoothProfile.STATE_CONNECTED) {
// flag = a2dp;
// }
// else if (headset == BluetoothProfile.STATE_CONNECTED) {
// flag = headset;
// }
// else if (health == BluetoothProfile.STATE_CONNECTED) {
// flag = health;
// }
//
// if (flag != -1) {
// bluetoothAdapter.getProfileProxy(mcContext, new BluetoothProfile.ServiceListener() {
//
// @Override
// public void onServiceDisconnected(int profile) {
// listener.disConnected();
// Log.i("", "hh=======onServiceDisconnected=>>");
// }
// @Override
// public void onServiceConnected(int profile, BluetoothProfile proxy) {
// Log.i("", "hh=======onServiceConnected=>>"+profile);
// List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
// listener.getConnectingDvice(mDevices);
// }
// }, flag);
// }else{
// listener.disConnected();
// }
// }
}
蓝牙音箱BluetoothA2dp的更多相关文章
- win7系统电脑连接小米蓝牙音箱
一.买好蓝牙适配器,插到电脑上. 二.右下角工具栏找到蓝牙图标 三.右键这个图标,选择'显示Bluetooth设备' 四.找到小米蓝牙音箱 'NDZ-030-AA' 五.双击打开它,然后选择'服务'选 ...
- 专业语音芯片MT8516 华为AM08蓝牙音箱
天猫精灵和亚马逊专用的语音芯片哦!联发科! 华为AM08蓝牙音箱 WT51F5161T的8052 微处理器,RC内振12MHz,具有16Kx8 的flash,硬件IIC,SPI,CEC,IR,RTC, ...
- 利用MediaSession发送信息到蓝牙音箱
1.利用MediaSession发送信息到蓝牙音箱,如:播放音乐时接收的歌曲信息,但是每一首歌连续播放时,再次发送的重复信息会被丢弃.则利用MediaSession发现信息时,要保证信息的不重复性. ...
- BluetoothA2dp蓝牙音箱的连接
1:权限 <uses-feature android:name="android.hardware.bluetooth_le" android:required=" ...
- 蓝牙音箱bose soundlink mini2链接mac后itunes自动启动的问题解决
1.在应用程序列表中复制一个应用重命名为DoNothingApp.app(非系统应用才可以成功复制) 2.打开terminal执行该命令(执行后需要输入密码),注意mv和iTunes.app后分别有一 ...
- 海美迪Q5智能机顶盒的蓝牙功能
虽然在硬件上,海美迪Q5智能机顶盒没有集成蓝牙模块,但是在软件系统上,Q5是支持蓝牙驱动的,所以它可以通过USB外接蓝牙适配器来扩展出蓝牙功能,简单来说,就是你另外买个蓝牙适配器,插到Q5上面,就能用 ...
- 天猫精灵X1智能音箱使用感想
11.22音箱到手,等了刚好一个月. 主要是测评语音交互功能. 测试条件:正宗普通话. 1)问天气.温度:表现良好.2)找手机功能:试了多次,每次都说手机号码格式不对3)小孩听故事:正常.但是开头会有 ...
- 基于Orangpi Zero和Linux ALSA实现WIFI无线音箱(一)
作品已经完成,先上源码: https://files.cnblogs.com/files/qzrzq1/WIFISpeaker.zip 全文包含三篇,这是第一篇,作为前言和概述. 第二篇:基于Oran ...
- 蓝牙speaker配对流程源码分析
这篇文章简单分析一下 蓝牙音箱配对流程.现在的音箱基本都支持security simple pairing.所以这里的流程基本上就是ssp的代码流程. 源码参考的是 Android 6.0 上面的bl ...
随机推荐
- (转)RabbitMQ学习之安装
http://blog.csdn.net/zhu_tianwei/article/details/40832185 RabbitMQ是一个开源的AMQP实现,服务器端用Erlang语言编写,支持多种客 ...
- MongoDB_可视化工具Robo 3T
Robo 3T可以对MongoDB进行可视化操作. Robo 3T安装 官网下载地址:https://robomongo.org/ 进入官网,点击下载,Studio 3T功能更全面,基础功能是免费的, ...
- 转载:rem的用法
本文属于转载,为尊重原作者的劳动成果,在此标注原文地址,点击此处浏览. 1.rem(font size of the root element)是指相对于根元素的字体大小的单位,em(font siz ...
- HILLSTONE sg6000 g5150 怎么恢复出厂设置
hillstone恢复出厂设置的方法(忘记密码的情况) 口令丢失情况下的处理 如果口令丢失,用户无法登录安全路由器进行配置,请在安全路由器刚启动时按住 CLR 按键大约 5 秒,使设备恢复到出厂配置. ...
- bzoj 1191: [HNOI2006]超级英雄Hero 网络流_残量网络
题目描述: 现在电视台有一种节目叫做超级英雄,大概的流程就是每位选手到台上回答主持人的几个问题,然后根据回答问题的 多少获得不同数目的奖品或奖金.主持人问题准备了若干道题目,只有当选手正确回答一道题后 ...
- 【hdu 6342】Expression in Memories
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 把所有的问号都改成'1' 然后会发现只有+0?这种情况 需要把?改成+. 看看这样的0后面的1是不是由问号改过来的就好了.是的话 再 ...
- powershell远程访问
在服务器上打开powershell 1.winrm quickconfig 2.Enable-PSRemoting -Force 在客户端上打开powershell 1.Enter-PSSession ...
- 洛谷—— P2668 斗地主
https://www.luogu.org/problem/show?pid=2668 题目描述 牛牛最近迷上了一种叫斗地主的扑克游戏.斗地主是一种使用黑桃.红心.梅花.方片的A到K加上大小王的共54 ...
- 日志log配置理解
实际生产中,每天都有大量的日志生成,单个文件(FileAppender)已经不能满足要求,RollingFileAppender继承了FileAppender,并提供了更多的功能: 每天生成一个日志文 ...
- 浅析C++绑定到Lua的方法
注:原文也在公司内部论坛上发了 概述 尽管将C++对象绑定到Lua已经有tolua++(Cocos2d-x 3.0用的就是这个).LuaBridge(我们游戏client对这个库进行了改 ...