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;
}
}
};
}
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();
// }
// }
}