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的更多相关文章

  1. win7系统电脑连接小米蓝牙音箱

    一.买好蓝牙适配器,插到电脑上. 二.右下角工具栏找到蓝牙图标 三.右键这个图标,选择'显示Bluetooth设备' 四.找到小米蓝牙音箱 'NDZ-030-AA' 五.双击打开它,然后选择'服务'选 ...

  2. 专业语音芯片MT8516 华为AM08蓝牙音箱

    天猫精灵和亚马逊专用的语音芯片哦!联发科! 华为AM08蓝牙音箱 WT51F5161T的8052 微处理器,RC内振12MHz,具有16Kx8 的flash,硬件IIC,SPI,CEC,IR,RTC, ...

  3. 利用MediaSession发送信息到蓝牙音箱

    1.利用MediaSession发送信息到蓝牙音箱,如:播放音乐时接收的歌曲信息,但是每一首歌连续播放时,再次发送的重复信息会被丢弃.则利用MediaSession发现信息时,要保证信息的不重复性. ...

  4. BluetoothA2dp蓝牙音箱的连接

    1:权限 <uses-feature android:name="android.hardware.bluetooth_le" android:required=" ...

  5. 蓝牙音箱bose soundlink mini2链接mac后itunes自动启动的问题解决

    1.在应用程序列表中复制一个应用重命名为DoNothingApp.app(非系统应用才可以成功复制) 2.打开terminal执行该命令(执行后需要输入密码),注意mv和iTunes.app后分别有一 ...

  6. 海美迪Q5智能机顶盒的蓝牙功能

    虽然在硬件上,海美迪Q5智能机顶盒没有集成蓝牙模块,但是在软件系统上,Q5是支持蓝牙驱动的,所以它可以通过USB外接蓝牙适配器来扩展出蓝牙功能,简单来说,就是你另外买个蓝牙适配器,插到Q5上面,就能用 ...

  7. 天猫精灵X1智能音箱使用感想

    11.22音箱到手,等了刚好一个月. 主要是测评语音交互功能. 测试条件:正宗普通话. 1)问天气.温度:表现良好.2)找手机功能:试了多次,每次都说手机号码格式不对3)小孩听故事:正常.但是开头会有 ...

  8. 基于Orangpi Zero和Linux ALSA实现WIFI无线音箱(一)

    作品已经完成,先上源码: https://files.cnblogs.com/files/qzrzq1/WIFISpeaker.zip 全文包含三篇,这是第一篇,作为前言和概述. 第二篇:基于Oran ...

  9. 蓝牙speaker配对流程源码分析

    这篇文章简单分析一下 蓝牙音箱配对流程.现在的音箱基本都支持security simple pairing.所以这里的流程基本上就是ssp的代码流程. 源码参考的是 Android 6.0 上面的bl ...

随机推荐

  1. Python笔记8----DataFrame(二维)

    目录: DataFrame概念 DataFrame创建 基本操作 查看.索引 修改.删除 统计功能 条件筛选 合并 去除空值 4. 一些常用的函数 apply memory_usage pivot_t ...

  2. 原生node写一个静态资源服务器

    myanywhere 用原生node做一个简易阉割版的anywhere静态资源服务器,以提升对node与http的理解. 相关知识 es6及es7语法 http的相关网络知识 响应头 缓存相关 压缩相 ...

  3. [LUOGU2730] 魔板

    搜索水题.因为只有8个数,排列一共有40320种,直接bfs,判重就行了. 但是判重的时候直接用8进制表示的话要88的bool数组.这种操作太low了,于是我们可以用康托展开,降成8!. 康托展开其实 ...

  4. 谈谈python里面关于任务队列

    谈谈python里面关于任务队列 为什么要做任务队列 要回答这个问题我们首先看看在流水线上的案列,如果人的速度很慢,机器的速度比人的速度快很多,就会造成,机器生产的东西没有及时处理,越积越多,造成阻塞 ...

  5. django-5-自定义模板过滤器及标签

    <<<代码布局(自定义的代码放哪里)>>> (1)某个app特有的  1.一般放app目录下 固定名为templatetags 的python文件夹里鸭,如果是别的 ...

  6. spring和struts整合

    整合准备:导入jar包 如果只是访问action,没有做数据库方面的操作的话 只需要导入下面的jar spring相关jar 以及struts相关jar包 整合过程: 用到了struts所以需要在we ...

  7. Virtual address cache memory, processor and multiprocessor

    An embodiment provides a virtual address cache memory including: a TLB virtual page memory configure ...

  8. Oracle 高水位(HWM: High Water Mark)

    http://blog.itpub.net/31397003/viewspace-2137246/ http://blog.itpub.net/12778571/viewspace-582695/ h ...

  9. NHibernate之旅(18):初探代码生成工具使用

    本节内容 引入 代码生成工具 结语 引入 我们花了大量的篇幅介绍了相关NHibernate的知识.一直都是带着大家手动编写代码,首先创建数据库架构.然后编写持久化类和映射文件,最后编写数据操作方法.測 ...

  10. 【SSH2框架(理论篇)】--SSH2 Vs 经典三层

     这几天一直在学习使用SSH2框架.对于框架本身的使用并非非常困难.相信经过多锻炼就行熟练的掌握框架的使用,让我匪夷所思的是在使用框架的时候感觉非常熟悉,好像在哪里用过似得. 就在某次查看代码的时 ...