Android Open Source - BHRelay Bluetooth Util






From Project

Back to project page BHRelay.

License

The source code is released under:

GNU General Public License

If you think the Android project BHRelay listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.sjtu.bhrelay.util;
/*from  www  .j  ava2s  .  c om*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.Thread.State;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;

import com.sjtu.bhrelay.BHSearchActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

public class BluetoothUtil {
  public static final String TAG = "BluetoothUtil";
  
  public static final int MODE_CLIENT = 101;
  public static final int MODE_SERVER = 102;
  
  public static void Broadcast(String action,Bundle bundle,Context context){
    Intent intent = new Intent();
        intent.setAction(action);
        if(bundle != null){
          intent.putExtras(bundle);
        }
        context.sendBroadcast(intent);
  }
  
  public static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
  
  public interface DataRecievedInterface{
    abstract public void onDataRecieved(String data);
    abstract public void onError(String error);
  }
  
  public interface StateChangedInterface{
    abstract public void onStateChanged();
    abstract public void onError();
  }
  
  private BluetoothBroadcastReciever mBroadcastReceiver;
  private IntentFilter intentFilter;
  private Context mcontext;
  
  private BluetoothDevice bhDev;
  private UUID uuid;
  private BluetoothAdapter bhAdapter;  
  private BluetoothSocket bhIOSocket = null;
  private OutputStream bhOutputStream = null;
  private InputThread inputThread = null;
  private ServerThread serverThread = null;
  private int mode;
  
  public BluetoothUtil(Context context,int mode){
    Log.e(TAG,"init");
    mcontext = context;
    
    bhAdapter = BluetoothAdapter.getDefaultAdapter();
    uuid = UUID.fromString(SPP_UUID);
    this.mode = mode;
    
    if(bhAdapter == null){
      Log.e(TAG,"no bluetooth device");
      
    }else{
      
      if(mode == BluetoothUtil.MODE_CLIENT){
        intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); 
        intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);  
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);  
        mBroadcastReceiver = new BluetoothBroadcastReciever();
        context.registerReceiver(mBroadcastReceiver,intentFilter);
        
      } 
    }
  }

  
  public void ClientConnect(String address){
    
    Log.e(TAG,"start bluetooth connect");
    bhDev = bhAdapter.getRemoteDevice(address);
    bhAdapter.cancelDiscovery();          
    CheckBondAndConnect();
  }
  
  private void CheckBondAndConnect(){
    Log.e(TAG,"check bond and connect");
    int BH_connstate = bhDev.getBondState();
    switch(BH_connstate){
    case BluetoothDevice.BOND_NONE:
      Log.e(TAG,"bond none");
      try {  
                Method createBondMethod = BluetoothDevice.class.getMethod("createBond");  
                createBondMethod.invoke(bhDev);  
            } catch (Exception e) {   
                e.printStackTrace();  
            }  
      break;
    case BluetoothDevice.BOND_BONDED:
      Log.e(TAG,"bonded and start bluetooth connect!");
      
      try {
        bhIOSocket = bhDev.createRfcommSocketToServiceRecord(uuid);
        bhIOSocket.connect();
        inputThread = new InputThread();
        inputThread.Start();
      } catch (IOException e) {
        Log.e(TAG,"bluetooth connect fail");
        e.printStackTrace();
      }
      
      break;
    case BluetoothDevice.BOND_BONDING:
      Log.e(TAG,"bonding...");
      break;
    default:
      Log.e(TAG,"other bond state");
      break;
    }
  }
  
  public void ClientDisConnect(){
    Log.e(TAG,"disconnect");
    inputThread.Stop();
  }
  
  public void StartServer(){
    Log.e(TAG,"StartServer");
    serverThread=new ServerThread();
    serverThread.Start();
    
    Intent discoverAbleIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverAbleIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 30);
    mcontext.startActivity(discoverAbleIntent);
    
  }
  
  public void StopServer(){
    Log.e(TAG,"StopServer");
    serverThread.Stop();
    
  }
  
  public String GetState(){
    Log.e(TAG,"get state");
    String state;
    if(null != bhIOSocket && bhIOSocket.isConnected()){
      state = bhDev.getName() + "----" + bhDev.getAddress();
    }else{
      state = "disconnect";
    }
    return state;
  }
  
  public void Destroy(){
    Log.e(TAG,"destroy");
    mcontext.unregisterReceiver(mBroadcastReceiver);
    if(inputThread != null){
      inputThread.Stop();
    }
  }
  
  public void SendMessage(String msg){
    
  }
  
  private DataRecievedInterface data_recieved;
  
  public void setOnDataRecievedListener(DataRecievedInterface data_recieved){
    if(this.data_recieved != null){
      this.data_recieved = data_recieved;
    }
  }
  
  private class InputThread extends Thread {

    private String mTAG = "InputThread";
    private InputStream inStream = null;// ???????????
    private long wait;
    //private BluetoothSocket bhIOSocket = null;
    //private Thread thread;
    private String  encodeType ="utf-8";
    
    private boolean isRun = false;
    
    public InputThread() {
      Log.e(mTAG, "init");
      this.wait=5;
      //thread =new Thread(new ReadRunnable());
    }

    public void Stop() {
      Log.e(mTAG, "Stop");
      isRun = false;      
    }
    
    public void Start() {
      Log.e(mTAG, "Start");
      isRun = true;
      State state = this.getState();
      if(state == State.NEW){
        this.start();
      }else{
        this.resume();
      }
    }
    
    @Override
    public void run(){
      super.run();
      
      try {          
        inStream = bhIOSocket.getInputStream();
        bhOutputStream = bhIOSocket.getOutputStream();    
      } catch (IOException e) {
        Log.e(mTAG, "get Input Output stream creation failed.", e);            
      }
      int length = 64;
      Log.e(mTAG, "ReadRunnable run");
      while (isRun) {
        
        byte[] temp = new byte[length];

        //keep listening to InputStream while connected
        try{
          int len = inStream.read(temp,0,length-1);  
          if (len > 0) {
            byte[] btBuf = new byte[len];
            System.arraycopy(temp, 0, btBuf, 0, btBuf.length);  
            //????
                  String readStr = new String(btBuf,encodeType);
                  Log.e(mTAG,"recieved data:" + readStr);
                  if(data_recieved != null){
                    data_recieved.onDataRecieved(readStr);
                  }
                  
          }                   
                Thread.sleep(wait);// ????????????
        }catch (Exception e) {
          if(data_recieved != null){
                  data_recieved.onError(e.toString());
                }
          Log.e(mTAG,"bluetooth read error");
          e.printStackTrace();
          this.Stop();
          switch(mode){
          case BluetoothUtil.MODE_CLIENT:break;
          case BluetoothUtil.MODE_SERVER:
            serverThread.Start();
            break;
          default:break;
          }
        }        
                  
      }
      
      try {
        bhIOSocket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  private class ServerThread extends Thread{
    
    private String mTAG = "ServerThread";
    private BluetoothServerSocket serverSocket = null;
    private boolean isRun = false;
    public ServerThread(){
      
      BluetoothServerSocket tmpSocket = null; 
      
        
          
      Log.e(mTAG, "init");
      try {
        tmpSocket = bhAdapter.listenUsingRfcommWithServiceRecord("BluetoothServerRfcommOn", uuid);
        Log.e(mTAG,"init socket success");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e(mTAG,"init socket fail");
      }      
      serverSocket = tmpSocket;      
    }

    @Override
    public void run() {
      super.run();
      Log.e(mTAG,"run");
      while(isRun){
              try{
                  bhIOSocket = serverSocket.accept();
                  Log.e(mTAG, "BluetoothSocket established! DataLink open.");
                //?????;
                Log.e(mTAG, "open bluetooth");
                //????????
              inputThread=new InputThread();
              Log.e(mTAG, "start thread");
              inputThread.Start(); 
              break;
              } catch (IOException e) {
                  break;
              }
              
          }
      
      Log.e(mTAG, "thread finish");
        this.Stop();
    }

    public void Start() {
      Log.e(mTAG,"Start");
      isRun = true;
      this.start();
    }
    
    public void Stop(){
      Log.e(mTAG,"Stop");
      isRun = false;
      try {
        serverSocket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  
  private class BluetoothBroadcastReciever extends BroadcastReceiver{
    
    private String mTAG = "BluetoothBroadcastReciever";
    
    public BluetoothBroadcastReciever(){
      super();
    }
    
    @Override
    public void onReceive(Context context, Intent intent) {
      
      Log.e(mTAG,"received");
      String action = intent.getAction();
      if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
        Log.e(mTAG,"action bond state change");
        CheckBondAndConnect();
      }
    }
    
  }
}




Java Source Code List

com.sjtu.bhrelay.BHSearchActivity.java
com.sjtu.bhrelay.MainActivity.java
com.sjtu.bhrelay.service.BGService.java
com.sjtu.bhrelay.util.BluetoothUtil.java
com.sjtu.bhrelay.util.TcpUtil.java