蓝牙音箱BluetoothA2dp

  1 package myapplication.com.mybuletooch;
  2 
  3 import android.support.v7.app.AppCompatActivity;
  4 import android.os.Bundle;
  5 import android.bluetooth.BluetoothA2dp;
  6 import android.bluetooth.BluetoothAdapter;
  7 import android.bluetooth.BluetoothDevice;
  8 import android.bluetooth.BluetoothHeadset;
  9 import android.bluetooth.BluetoothProfile;
 10 import android.bluetooth.BluetoothSocket;
 11 import android.content.BroadcastReceiver;
 12 import android.content.ComponentName;
 13 import android.content.Context;
 14 import android.content.Intent;
 15 import android.content.IntentFilter;
 16 import android.content.pm.PackageManager;
 17 import android.content.pm.ResolveInfo;
 18 import android.net.Uri;
 19 import android.os.Build;
 20 import android.support.v7.app.AppCompatActivity;
 21 import android.os.Bundle;
 22 import android.util.Log;
 23 import android.view.View;
 24 import android.widget.AdapterView;
 25 import android.widget.ArrayAdapter;
 26 import android.widget.ListView;
 27 import android.widget.Toast;
 28 
 29 import java.io.File;
 30 import java.io.IOException;
 31 import java.lang.reflect.Method;
 32 import java.util.ArrayList;
 33 import java.util.List;
 34 import java.util.UUID;
 35 
 36 public class MainActivity extends AppCompatActivity {
 37     BluetoothAdapter adapter;
 38     ArrayList<String> datas = new ArrayList<String>();
 39     ListView listv;
 40     ArrayAdapter<String> ad;
 41     BluetoothDevice remoteD;
 42     List<BluetoothDevice> mBluetoothDevices;
 43 
 44     @Override
 45     protected void onCreate(Bundle savedInstanceState) {
 46         super.onCreate(savedInstanceState);
 47         setContentView(R.layout.activity_main);
 48         init();
 49         initView();
 50     }
 51 
 52     private void initView() {
 53         listv = (ListView) findViewById(R.id.listView);
 54         listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 55             @Override
 56             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 57                 String bl = datas.get(position);
 58                 //使用"-"分割字符串
 59                 String[] values = bl.split("-");
 60 //                connect(mBluetoothDevices.get(position).getAddress(), position);
 61 //                connect(values[values.length - 1]);
 62 //                connect(mBluetoothDevices.get(position));
 63 //                Toast.makeText(MainActivity.this, mBluetoothDevices.get(position).getAddress(), Toast.LENGTH_SHORT).show();
 64             }
 65         });
 66         ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, datas);
 67         listv.setAdapter(ad);
 68 
 69     }
 70 
 71 
 72 
 73     //初始化
 74     private void init() {
 75         mBluetoothDevices = new ArrayList<>();
 76         IntentFilter filter = new IntentFilter();
 77         filter.addAction(BluetoothDevice.ACTION_FOUND);
 78         //动态注册广播接收器
 79         this.registerReceiver(receiver, filter);
 80 
 81     }
 82 
 83 
 84 
 85     class A extends BroadcastReceiver {
 86         @Override
 87         public void onReceive(Context context, Intent intent) {
 88 
 89             if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
 90                 //获取扫描到的设备
 91                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 92                 mBluetoothDevices.add(device);
 93 
 94                 String name = device.getName();
 95                 String address = device.getAddress();
 96                 System.out.println("--扫到的设备:" + name + ":" + address);
 97                 //数据变化了
 98 
 99                 datas.add(name + "-" + address);
100                 //刷新列表
101                 ad.notifyDataSetChanged();
102             }
103         }
104     }
105 
106 
107 
108 
109     private BroadcastReceiver receiver = new BroadcastReceiver() {
110         @Override
111         public void onReceive(Context context, Intent intent) {
112             String action = intent.getAction();
113             if (BluetoothDevice.ACTION_FOUND.equals(action)) {
114                 // 获取查找到的蓝牙设备
115                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
116                 System.out.println(device.getName());
117                 // 如果查找到的设备符合要连接的设备,处理
118                 String name = device.getName();
119                 String address = device.getAddress();
120                 System.out.println("--扫到的设备:" + name + ":" + address);
121                 //数据变化了
122                 datas.add(name + "-" + address);
123                 //刷新列表
124                 ad.notifyDataSetChanged();
125                 // 搜索蓝牙设备的过程占用资源比较多,一旦找到需要连接的设备后需要及时关闭搜索
126                 adapter.cancelDiscovery();
127                 // 获取蓝牙设备的连接状态
128                 int connectState = device.getBondState();
129                 remoteD = device;
130                 switch (connectState) {
131                     // 未配对
132                     case BluetoothDevice.BOND_NONE:
133                         Log.i("走配对", "onReceive: " + "走配对方法了");
134                         // 配对
135                         try {
136                             Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
137                             createBondMethod.invoke(device);
138                         } catch (Exception e) {
139                             e.printStackTrace();
140                         }
141                         break;
142                     // 已配对
143                     case BluetoothDevice.BOND_BONDED:
144                         // 连接
145 //                        new ConnectThread(device).start();
146                         adapter.getProfileProxy(getApplicationContext(), mA2dpProfileListener, BluetoothProfile.A2DP);
147                         adapter.getProfileProxy(getApplicationContext(), mHeadsetProfileListener, BluetoothProfile.HEADSET);
148                         Log.i("走连接方法啦", "onReceive: ");
149                         break;
150                 }
151             } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
152                 // 状态改变的广播
153                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
154 
155                 int connectState = device.getBondState();
156                 remoteD = device;
157                 switch (connectState) {
158                     case BluetoothDevice.BOND_NONE:
159                         break;
160                     case BluetoothDevice.BOND_BONDING:
161                         break;
162                     case BluetoothDevice.BOND_BONDED:
163                         // 连接
164                         Log.i("走连接方法啦", "onReceive: ");
165 //                        connect(device);
166 //                        new ConnectThread(device).start();
167                         break;
168                 }
169 
170             }
171         }
172     };
173     BluetoothA2dp mBluetoothA2dp;
174     private BluetoothProfile.ServiceListener mA2dpProfileListener = new BluetoothProfile.ServiceListener() {
175         public void onServiceConnected(int profile, BluetoothProfile proxy) {
176             if (profile == BluetoothProfile.A2DP) {
177                 mBluetoothA2dp = (BluetoothA2dp) proxy;
178                 try {
179                     ClsUtils.connect(mBluetoothA2dp.getClass(), mBluetoothA2dp, remoteD);
180                 } catch (Exception e) {
181                     adapter.closeProfileProxy(BluetoothProfile.A2DP, mBluetoothA2dp);
182                     e.printStackTrace();
183                 }
184             }
185         }
186 
187         public void onServiceDisconnected(int profile) {
188             if (profile == BluetoothProfile.A2DP) {
189                 mBluetoothA2dp = null;
190             }
191         }
192     };
193 
194     /**
195      * @Fields mHeadsetProfileListener : BluetoothHeadset服务监听器
196      */
197     BluetoothHeadset mBluetoothHeadset;
198     private BluetoothProfile.ServiceListener mHeadsetProfileListener = new BluetoothProfile.ServiceListener() {
199         public void onServiceConnected(int profile, BluetoothProfile proxy) {
200             if (profile == BluetoothProfile.HEADSET) {
201                 mBluetoothHeadset = (BluetoothHeadset) proxy;
202                 try {
203 
204                     ClsUtils.connect(mBluetoothHeadset.getClass(), mBluetoothHeadset, remoteD);
205                 } catch (Exception e) {
206                     adapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
207                     e.printStackTrace();
208                 }
209             }
210         }
211 
212         public void onServiceDisconnected(int profile) {
213             if (profile == BluetoothProfile.HEADSET) {
214                 mBluetoothHeadset = null;
215             }
216         }
217     };
218 
219    
220 
221 }
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();
//        }
//    }
}
今天多一点积累,明天少一分烦恼
原文地址:https://www.cnblogs.com/galibujianbusana/p/5944918.html