Java tutorial
/* Copyright 2015 Jianan - qinxiandiqi@foxmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.molidt.easyandroid.bluetooth; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothProfile.ServiceListener; import android.bluetooth.BluetoothServerSocket; 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.ServiceConnection; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.v4.BuildConfig; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * You should call {@link BluetoothFragmentV4#addBluetoothPlugin(android.support.v4.app.FragmentActivity)} to use this fragment * @author Jianan */ public class BluetoothFragmentV4 extends Fragment { public static final int REQUEST_ENABLE_BT = 6000; public static final int REQUEST_DISCOVERABLE = 6001; // Stops scanning after 12 seconds. public static final long SCAN_PERIOD = 12000; public static final int INVALID_RESULT = -999; public static final String BLUETOOTH_FRAGMENT_TAG = "BLUETOOTH"; /** * Default value is generated by the package name. */ private static UUID BLUETOOTH_UUID = null; private Activity _activity; private Handler _Handler; private BluetoothAdapter mBluetoothAdapter; private boolean isSupportBluetooth = false; private boolean isSupportBLE = false; private boolean isScanning = false; private boolean isInit = false; private List<BluetoothDevice> mDiscoveryFoundDevices = new ArrayList<BluetoothDevice>(); private Map<String, ConnectingServerThread> mServerThreadMap = new HashMap<String, ConnectingServerThread>(); private Map<String, ConnectingClientThread> mClientThreadMap = new HashMap<String, ConnectingClientThread>(); private BluetoothLeService mBluetoothLeService; private BluetoothStateListener mBluetoothStateListener; private DiscoveryBluetoothDeviceListener mDiscoveryBluetoothDeviceListener; private DiscoverableModeListener mDiscoverableModeListener; @Override public void onAttach(Activity activity) { super.onAttach(activity); _activity = activity; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { if (mBluetoothStateListener != null) mBluetoothStateListener.enableBluetoothSuccess(); } else if (resultCode == Activity.RESULT_CANCELED) { if (mBluetoothStateListener != null) mBluetoothStateListener.enableBluetoothFail(); } } else if (requestCode == REQUEST_DISCOVERABLE) { if (requestCode == Activity.RESULT_OK) { if (mDiscoverableModeListener != null) mDiscoverableModeListener.enableDiscoverableSuccess(); } else if (requestCode == Activity.RESULT_CANCELED) { if (mDiscoverableModeListener != null) mDiscoverableModeListener.enableDiscoverableFial(); } } super.onActivityResult(requestCode, resultCode, data); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!isInit) { initPlugin(_activity); } _Handler = new Handler(); //if UUID is null,using the package name to setting the default UUID if (BLUETOOTH_UUID == null) { BLUETOOTH_UUID = UUID.fromString(_activity.getPackageName()); } IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); _activity.registerReceiver(mFoundReceiver, filter); if (isSupportBLE) { Intent gattServiceIntent = new Intent(_activity, BluetoothLeService.class); _activity.bindService(gattServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE); } } @Override public void onDestroy() { _activity.unregisterReceiver(mFoundReceiver); if (isSupportBLE && mBluetoothLeService != null && mBluetoothLeService.getBLEConnectedSize() <= 0) { _activity.unbindService(mServiceConnection); } super.onDestroy(); } /** * You should call this method to add bluetooth feature.This method will auto begin transcation to add fragment, * so you don't need to call SupportFragmentManager and add fragment. * @param activity * @return */ public static BluetoothFragmentV4 addBluetoothPlugin(FragmentActivity activity) { BluetoothFragmentV4 fragment = new BluetoothFragmentV4(); fragment.initPlugin(activity); activity.getSupportFragmentManager().beginTransaction().add(fragment, BLUETOOTH_FRAGMENT_TAG).commit(); return fragment; } protected void initPlugin(Activity activity) { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); _activity = activity; if (mBluetoothAdapter == null) { isSupportBluetooth = false; isSupportBLE = false; } else { isSupportBluetooth = true; if (_activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { isSupportBLE = true; } else { isSupportBLE = false; } } isInit = true; } public boolean isSupportBluetooth() { return isSupportBluetooth; } public boolean isSupportBLE() { return isSupportBLE; } public boolean isBluetoothEnable() { return mBluetoothAdapter.isEnabled(); } public void setUUID(UUID uuid) { BLUETOOTH_UUID = uuid; } public void setUUID(String uuid) { BLUETOOTH_UUID = UUID.fromString(uuid); } //enable bluetooth switch /** * If you want to get the callback result, please use * {@link #setBluetoothStateListener(BluetoothFragmentV4.BluetoothStateListener)} before * or usd {@link #setBluetoothEnable(BluetoothFragmentV4.BluetoothStateListener)} directly */ public void setBluetoothEnable() { if (isSupportBluetooth) { if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } } public void setBluetoothEnable(BluetoothStateListener listener) { mBluetoothStateListener = listener; setBluetoothEnable(); } public void setBluetoothStateListener(BluetoothStateListener listener) { mBluetoothStateListener = listener; } public void removeBluetoothStateListener() { mBluetoothStateListener = null; } //get paired Devices public Set<BluetoothDevice> getPairedDevices() { return mBluetoothAdapter.getBondedDevices(); } //discovery bluetooth devices /** * Start to scan bluetooth devices.If it is scaning classic bluetooth devices or BLE devices, calling this method will return false directly. * By the way,if the bluetooth's mode isn't {@link BluetoothAdapter#STATE_ON} now, it also will return false. * @param listener * @return */ public boolean startDiscovery(DiscoveryBluetoothDeviceListener listener) { if (isScanning) return false; mDiscoveryBluetoothDeviceListener = listener; isScanning = mBluetoothAdapter.startDiscovery(); return isScanning; } public void removeDiscoveryBluetoothDeviceListener() { mDiscoveryBluetoothDeviceListener = null; } public void cancelDiscovery() { isScanning = false; mBluetoothAdapter.cancelDiscovery(); } //discoverable setting public void setDiscoverable(int discoveralbeTime) { Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, discoveralbeTime); startActivity(discoverableIntent); } public void setDiscoverable(int discoverableTime, DiscoverableModeListener listener) { mDiscoverableModeListener = listener; setDiscoverable(discoverableTime); } public void setDiscoverableModeListener(DiscoverableModeListener listener) { mDiscoverableModeListener = listener; } public void removeDiscoverableModeListener() { mDiscoverableModeListener = null; } //connecting as a server /** * Using the default UUID to start a BluetoothServerSocket listening bluetooth connecting requests. * @param listener */ public void startConnectionAsServer(BluetoothServerSocketListener listener) { startConnectionAsServer(BLUETOOTH_UUID, listener); } /** * Start a BluetoothServerSocket to listen bluetooth connecting requests. * @param uuid * @param listener */ public void startConnectionAsServer(UUID uuid, BluetoothServerSocketListener listener) { cancelDiscovery(); ConnectingServerThread serverThread = mServerThreadMap.get(uuid.toString()); if (serverThread == null || !serverThread.isAlive()) { serverThread = new ConnectingServerThread(uuid, listener); mServerThreadMap.put(uuid.toString(), serverThread); serverThread.start(); } } /** * Stop the BluetoothServerSocet which build by the defualt UUID. */ public void stopConnectionAsServer() { stopConnectionAsServer(BLUETOOTH_UUID); } /** * Stop the BluetoothServerSocket which build the the UUID it used. * @param uuid */ public void stopConnectionAsServer(UUID uuid) { ConnectingServerThread serverThread = mServerThreadMap.get(uuid.toString()); if (serverThread != null) { serverThread.cancel(); mServerThreadMap.remove(uuid.toString()); } } //connectiong as a client /** * Using the BluetoothDevice and defualt UUID to build the connection. * @param device * @param listener */ public void startConnectionAsClient(BluetoothDevice device, BluetoothSocketListener listener) { startConnectionAsClient(device, BLUETOOTH_UUID, listener); } /** * Uding the BluetoothDevice and UUID to build the connection. * @param device * @param uuid * @param listener */ public void startConnectionAsClient(BluetoothDevice device, UUID uuid, BluetoothSocketListener listener) { String key = getDeviceKey(device, uuid); ConnectingClientThread thread = mClientThreadMap.get(key); if (thread == null || !thread.isAlive()) { thread = new ConnectingClientThread(device, uuid, listener); mClientThreadMap.put(key, thread); thread.start(); } } /** * Stop the connecting process which the BluetoothDevice request by the defualt UUID. * @param device */ public void stopConnectionAsClient(BluetoothDevice device) { stopConnectionAsClient(device, BLUETOOTH_UUID); } /** * Stop the connection process which the BluetoothDevice request by UUID. * @param device * @param uuid */ public void stopConnectionAsClient(BluetoothDevice device, UUID uuid) { String key = getDeviceKey(device, uuid); ConnectingClientThread thread = mClientThreadMap.get(key); if (thread != null) { thread.cancel(); mClientThreadMap.remove(key); } } private String getDeviceKey(BluetoothDevice device, UUID uuid) { return device.getAddress() + "_" + uuid.toString(); } //build connection /** * Get the connection by socket which have connected.If the socket havn't connected,it return null. * @param socket * @param intBufferSize the buffer size of reading byte cache. * @param listener * @return */ public BluetoothConnection getBluetoothConnection(BluetoothSocket socket, int intBufferSize, BluetoothConnectionListener listener) { BluetoothConnection connection = new BluetoothConnection(socket, intBufferSize, listener); connection.start(); return connection; } //BluetoothProfile /** * see {@link BluetoothAdapter#getProfileProxy(Context, ServiceListener, int)} * @param listener * @param profile */ @SuppressLint("NewApi") public boolean getProfileProxy(ServiceListener listener, int profile) { return mBluetoothAdapter.getProfileProxy(_activity, listener, profile); } /** * scan BLE devices within 12s * @param isEnable if true then start to scan,if false then stop or cancel scan progress. * @param leScanCallback when discovery a BLE device will callback * @return */ public boolean setScanBLEDevice(boolean isEnable, final BluetoothAdapter.LeScanCallback leScanCallback) { return setScanBLEDevice(isEnable, SCAN_PERIOD, leScanCallback); } /** * scan BLE devices * @param isEnable if true then start to scan,if false then stop or cancel scan progress. * @param scanMillis scanning time * @param leScanCallback when discovery a BLE device will callback * @return */ public boolean setScanBLEDevice(boolean isEnable, long scanMillis, final BluetoothAdapter.LeScanCallback leScanCallback) { return setScanBLEDevice(isEnable, null, scanMillis, leScanCallback); } /** * scan BLE device by uuids. * @param isEnable if true then start to scan,if false then stop or cancel scan progress. * @param uuids the target uuid array. * @param scanMillis scanning time * @param leScanCallback when discovery a BLE device will callback * @return if true,it was started or stoped successful. */ @SuppressLint("NewApi") public boolean setScanBLEDevice(boolean isEnable, UUID[] uuids, long scanMillis, final BluetoothAdapter.LeScanCallback leScanCallback) { if (isEnable) { if (isScanning) return false; _Handler.postDelayed(new Runnable() { @Override public void run() { isScanning = false; mBluetoothAdapter.stopLeScan(leScanCallback); } }, scanMillis); if (uuids == null) { isScanning = mBluetoothAdapter.startLeScan(leScanCallback); } else { isScanning = mBluetoothAdapter.startLeScan(uuids, leScanCallback); } return isScanning; } else { isScanning = false; mBluetoothAdapter.stopLeScan(leScanCallback); return true; } } /** * see {@link BluetoothLeService#connect(String, boolean, BluetoothGattCallback)} * @param address * @param isAutoConnect * @param callback * @return */ public boolean connectBLE(String address, boolean isAutoConnect, BluetoothGattCallback callback) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.connect(address, isAutoConnect, callback); } /** * see {@link BluetoothLeService#connect(BluetoothDevice, boolean, BluetoothGattCallback)} * @param device * @param isAutoConnect * @param callback * @return */ public boolean connectBLE(BluetoothDevice device, boolean isAutoConnect, BluetoothGattCallback callback) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.connect(device, isAutoConnect, callback); } /** * see {@link BluetoothLeService#disconnect(String)} * @param address * @return */ public boolean disconnectBLE(String address) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.disconnect(address); } /** * see {@link BluetoothLeService#disconnect(BluetoothDevice)} * @param device * @return */ public boolean disconnectBLE(BluetoothDevice device) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.disconnect(device); } /** * see {@link BluetoothLeService#close(String)} * @param address * @return */ public boolean closeBLE(String address) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.close(address); } /** * see {@link BluetoothLeService#close(BluetoothDevice)} * @param device * @return */ public boolean closeBLE(BluetoothDevice device) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.close(device); } /** * see {@link BluetoothLeService#closeAll()} * @return */ public boolean closeAllBLE() { if (mBluetoothLeService == null) return false; mBluetoothLeService.closeAll(); return true; } /** * see {@link BluetoothLeService#readCharacteristic(String, BluetoothGattCharacteristic)} * @param address * @param characteristic * @return */ public boolean readBLECharacteristic(String address, BluetoothGattCharacteristic characteristic) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.readCharacteristic(address, characteristic); } /** * see {@link BluetoothLeService#readCharacteristic(BluetoothDevice, BluetoothGattCharacteristic)} * @param device * @param characteristic * @return */ public boolean readBLECharacteristic(BluetoothDevice device, BluetoothGattCharacteristic characteristic) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.readCharacteristic(device, characteristic); } /** * see {@link BluetoothLeService#setCharacteristicNotification(String, BluetoothGattCharacteristic, boolean)} * @param address * @param characteristic * @param enabled * @return */ public boolean setBLECharacteristicNotification(String address, BluetoothGattCharacteristic characteristic, boolean enabled) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.setCharacteristicNotification(address, characteristic, enabled); } /** * see {@link BluetoothLeService#setCharacteristicNotification(BluetoothDevice, BluetoothGattCharacteristic, boolean)} * @param device * @param characteristic * @param enabled * @return */ public boolean setBLECharacteristicNotification(BluetoothDevice device, BluetoothGattCharacteristic characteristic, boolean enabled) { if (mBluetoothLeService == null) return false; return mBluetoothLeService.setCharacteristicNotification(device, characteristic, enabled); } /** * see {@link BluetoothLeService#getSupportedGattServices(String)} * @param address * @return */ public List<BluetoothGattService> getBLESupportedGattServices(String address) { if (mBluetoothLeService == null) return null; return mBluetoothLeService.getSupportedGattServices(address); } /** * see {@link BluetoothLeService#getSupportedGattServices(BluetoothDevice)} * @param device * @return */ public List<BluetoothGattService> getBLESupportedGattServices(BluetoothDevice device) { if (mBluetoothLeService == null) return null; return mBluetoothLeService.getSupportedGattServices(device); } private BroadcastReceiver mFoundReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { int previousState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, INVALID_RESULT); int nowState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, INVALID_RESULT); if (mBluetoothStateListener != null) mBluetoothStateListener.stateChange(previousState, nowState); } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { isScanning = true; if (mDiscoveryBluetoothDeviceListener != null) mDiscoveryBluetoothDeviceListener.startDiscovery(); } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); BluetoothClass bluetoothClass = intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS); mDiscoveryFoundDevices.add(device); if (mDiscoveryBluetoothDeviceListener != null) mDiscoveryBluetoothDeviceListener.foundBluetoothDevice(device, bluetoothClass); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { isScanning = false; if (mDiscoveryBluetoothDeviceListener != null) mDiscoveryBluetoothDeviceListener.finishDiscovery(); } else if (BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) { int previousMode = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, INVALID_RESULT); int nowMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, INVALID_RESULT); if (mDiscoverableModeListener != null) mDiscoverableModeListener.modeChange(previousMode, nowMode); } } }; private final ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder service) { mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService(); if (!mBluetoothLeService.initialize()) { if (BuildConfig.DEBUG) Log.e(getClass().getName(), "Unable to initialize Bluetooth"); mBluetoothLeService = null; } } @Override public void onServiceDisconnected(ComponentName componentName) { mBluetoothLeService = null; } }; public class ConnectingServerThread extends Thread { private final BluetoothServerSocket mServerSocket; private final BluetoothServerSocketListener mListener; private final UUID mUUID; private boolean isRunning = true; public ConnectingServerThread(UUID uuid, BluetoothServerSocketListener listener) { mListener = listener; mUUID = uuid; BluetoothServerSocket temp = null; try { temp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(_activity.getPackageName(), mUUID); } catch (IOException e) { e.printStackTrace(); } mServerSocket = temp; isRunning = true; } @Override public void run() { BluetoothSocket socket = null; if (mListener == null) { try { mServerSocket.close(); } catch (IOException e) { e.printStackTrace(); } return; } while (isRunning) { try { socket = mServerSocket.accept(); } catch (IOException e) { e.printStackTrace(); if (mListener != null) mListener.closing(true, e); break; } if (socket != null) { if (mListener == null || !mListener.getSocket(socket)) { try { mServerSocket.close(); if (mListener != null) mListener.closing(false, null); } catch (IOException e) { e.printStackTrace(); if (mListener != null) mListener.closing(true, e); } break; } } } } public void cancel() { try { mServerSocket.close(); isRunning = false; if (!isAlive() && mListener != null) { mListener.closing(false, null); } } catch (IOException e) { e.printStackTrace(); } } } public class ConnectingClientThread extends Thread { private final BluetoothDevice mDevice; private final BluetoothSocket mSocket; private final UUID mUUID; private final BluetoothSocketListener mListener; public ConnectingClientThread(BluetoothDevice device, UUID uuid, BluetoothSocketListener listener) { mDevice = device; mUUID = uuid; mListener = listener; BluetoothSocket temp = null; try { temp = mDevice.createRfcommSocketToServiceRecord(mUUID); } catch (IOException e) { e.printStackTrace(); } mSocket = temp; } @Override public void run() { cancelDiscovery(); try { mSocket.connect(); } catch (IOException e) { e.printStackTrace(); try { mSocket.close(); } catch (IOException e1) { e1.printStackTrace(); } if (mListener != null) mListener.closing(true, e); return; } if (mListener != null) { mListener.getSocket(mSocket); mListener.closing(false, null); } } public void cancel() { try { mSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } public class BluetoothConnection extends Thread { private final BluetoothSocket mSocket; private final BluetoothConnectionListener mListener; private final int mBufferSize; private final InputStream mIs; private final OutputStream mOs; private boolean isRunning = true; public BluetoothConnection(BluetoothSocket socket, int bufferSize, BluetoothConnectionListener listener) { mSocket = socket; mListener = listener; mBufferSize = bufferSize; InputStream tempIs = null; OutputStream tempOs = null; try { tempIs = mSocket.getInputStream(); tempOs = mSocket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } mIs = tempIs; mOs = tempOs; isRunning = true; } @Override public void run() { byte[] buffer = new byte[mBufferSize]; int bytes = 0; while (isRunning) { try { bytes = mIs.read(buffer); if (mListener != null) mListener.read(buffer, bytes); } catch (IOException e) { if (mListener != null) mListener.closing(true, e); break; } } } /** * Send byte data to the remote device * @param buffer * @return If the data is send successfully,it return true else is false. */ public boolean write(byte[] buffer) { try { mOs.write(buffer); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * To call this method,it would close itself but not immediately. */ public void close() { try { mSocket.close(); isRunning = false; if (!isAlive() && mListener != null) { mListener.closing(false, null); } } catch (IOException e) { e.printStackTrace(); } } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public boolean isConnected() { return mSocket.isConnected(); } /** * Get the remote device which is connecting. * @return */ public BluetoothDevice getRemoteDevice() { return mSocket.getRemoteDevice(); } } public interface BluetoothStateListener { /** * The possible values are <br> * {@link BluetoothAdapter#STATE_TURNING_ON}<br> * {@link BluetoothAdapter#STATE_TURNING_OFF}<br> * {@link BluetoothAdapter#STATE_ON}<br> * {@link BluetoothAdapter#STATE_OFF}<br> * {@link BluetoothFragmentV4#INVALID_RESULT} * @param previousState * @param nowState */ public void stateChange(int previousState, int nowState); public void enableBluetoothSuccess(); public void enableBluetoothFail(); } public interface DiscoveryBluetoothDeviceListener { public void startDiscovery(); public void finishDiscovery(); public void foundBluetoothDevice(BluetoothDevice device, BluetoothClass bluetoothClass); } public interface DiscoverableModeListener { /** * The possible values are<br> * {@link BluetoothAdapter#SCAN_MODE_CONNECTABLE_DISCOVERABLE}<br> * {@link BluetoothAdapter#SCAN_MODE_CONNECTABLE}<br> * {@link BluetoothAdapter#SCAN_MODE_NONE}<br> * {@link BluetoothFragmentV4#INVALID_RESULT} */ public void modeChange(int previousMode, int nowMode); public void enableDiscoverableSuccess(); public void enableDiscoverableFial(); } public interface BluetoothServerSocketListener { /** * When the BluetoothServerSocket connect to a remote device,this method would be callback. * If you want to keep listening another device's request,you should return true.Return false will cancel the server listening. * Remark:this method is not running in the UI thread. * @param socket * @return return false will stop connecting server thread,retrun true will go on. */ public boolean getSocket(BluetoothSocket socket); /** * The server maybe be closed because of an exception or running over. * Remark:this method maybe is not running in the UI thread. * @param hasError return true, there is an exception,else no exception. * @param e */ public void closing(boolean hasError, Exception e); } public interface BluetoothSocketListener { /** * When the BluetoothDevice connect to the remove device,this method would be callback,and the requesting conneciont thread will be finished. * Remark:this method is not running in the UI thread. * @param socket */ public void getSocket(BluetoothSocket socket); /** * The server maybe be closed because of an exception or running over. * Remark:this method is not running in the UI thread. * @param hasError return true, there is an exception,else no exception. * @param e */ public void closing(boolean hasError, Exception e); } public interface BluetoothConnectionListener { /** * When there is any data from remote bluetooth device,this method would be callback. * @param buffer the received data. * @param bytes the length of received data. */ public void read(byte[] buffer, int bytes); /** * The server maybe be closed because of an exception or running over. * Remark:this method maybe is not running in the UI thread. * @param hasError return true, there is an exception,else no exception. * @param e */ public void closing(boolean hasError, Exception e); } }