蓝牙音箱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 ...
随机推荐
- 【seo】title / robots / description / canonical
1.title title,就是浏览器上显示的那些内容,不仅用户能看到,也能被搜索引擎检索到(搜索引擎在抓取网页时,最先读取的就是网页标题,所以title是否正确设置极其重要. 1)title一般不超 ...
- spring boot (一)
spring boot 启动注解 @SpringBootApplication @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIM ...
- VS Code中html 如何查找标签(5)
1 添加几个标签 <body> <span>第一个span标签</span> <p>这是第一个p标签</p> <span>第二 ...
- Linux 命令查询系统负载信息
linux uptime命令主要用于获取主机运行时间和查询linux系统负载等信息.uptime命令过去只显示系统运行多久.现在,可以显示系统已经运行了多长 时间,信息显示依次为:现在时间.系统已经运 ...
- NOIP2016 天天爱跑步 线段树合并_桶_思维题
竟然独自想出来了,好开心 Code: #include<bits/stdc++.h> #define setIO(s) freopen(s".in","r&q ...
- node——模块化
之前写的新闻部分几乎所有操作都写在了一起,这次开始进行模块化. 为什么要模块化: 1.提高开发效率,所有操作在一个文件内,不方便团队操作,模块化可多人同时操作 2.当程序出错,可以分模块寻找错误 3. ...
- python海龟的使用
############################螺旋正方形############################### import turtle turtle.left(90)for i ...
- python与图灵机器人交互(WXPY版本)
开发者账号:wujunfeng , 开发者key:官网申请 #!/usr/bin/env python#-*- coding:utf-8 -*- @Author : wujf @Time:2018/ ...
- UNIX时间转换ASP代码.txt
'参数:strTime:要转换的时 间:intTimeZone:该时间对应的时区 '返回值:strTime相对于1970年1月1日午夜0点经过的秒数 '示例:ToUnixTime("2008 ...
- WEBGL学习【十】运动模型
<!DOCTYPE HTML> <html lang="en"> <head> <title>LWEBGL6.2, Animated ...