蓝牙音箱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 ...
随机推荐
- 使用QT的一些小Tipster
1.在使用Qt Creator编程时,难免会用到将float类型转换为QString类型的方法:原文 1.1. 将QString类型转化为float类型,很简单 QString data; ...
- matplotlib简介-高质量图形输出
Matplotlib 是一个用来绘制二维图形的 Python 模块,它克隆了许多 Matlab 中的函数, 用以帮助 Python 用户轻松获得高质量(达到出版水平)的二维图形. 文章来源:http: ...
- 模拟试题A
模拟试题A 一.单项选择题(2′*12=24′) 1.下面各种坐标变换中,会产生变换前后维度的改变的是( ) A)建模变换 B)观察变换 C)投影变换 D)视口变换 2.下列描述深度缓冲消隐算法的特点 ...
- 资深程序员总结:彻底理解Spring容器和应用上下文
点关注,不迷路:持续更新Java架构相关技术及资讯热文!!! 有了Spring之后,通过依赖注入的方式,我们的业务代码不用自己管理关联对象的生命周期.业务代码只需要按照业务本身的流程,走啊走啊,走到哪 ...
- 历年真题 未完成(Noip 2008 - Noip 2017)
Noip 2008 :全部 Noip 2009 :全部 Noip 2010 :AK Noip 2011 :AK Noip 2012 : Vigenère 密码,国王游戏,开车旅行 Noip 2013 ...
- kernel对NTP的API,系统调用函数
kenrel API for NTP kernel 提供两个API(即系统调用 system call)给应用程序NTP,去校准kernel system clock Kernel Applicati ...
- int rc = -EINVAL是什么意思
rc应该是return code的意思,将函数返回值rc初始化为-EINVAL,EINVAL由POSIX.1规范中的一个宏,一般通过包含C标准头文件errno.h,表示参数无效(invalid arg ...
- BZOJ 3110 [ZJOI2013]K大数查询 (整体二分+线段树)
和dynamic rankings这道题的思想一样 只不过是把树状数组换成线段树区间修改,求第$K$大的而不是第$K$小的 这道题还有负数,需要离散 #include <vector> # ...
- 交互式编程之Golang基本配置(Jupyter-notebooks Golang)
JupyterNoteBook-GO 启动错误 Install Go Install gophernotes 参考资料 如有错误,欢迎指出 错误 error: Cannot assign reques ...
- String类常见的方法
类String public final class String extends Object implements Serializable, comparable<String>, ...