2016-09-21 103 views
0

我正在尝试制作一个通过蓝牙套接字发送音频的应用程序。到目前为止,我已经达到了配对设备并启动连接线程(客户端)的程度,但它不起作用可能我会((现在我只是想发送文本))。 这是我的代码:蓝牙套接字不起作用Android

public class MainActivity extends Activity implements AdapterView.OnItemClickListener { 



String tag="debuger"; 
ArrayAdapter<String> listAdapter; 
Button connectNew; 
ListView listView; 
BluetoothAdapter btAdapter; 
ArrayList<BluetoothDevice> devices; 
Set<BluetoothDevice> deviceArray; 
IntentFilter filter; 
BroadcastReceiver receiver; 
ArrayList<String> pairedDevices; 

public static final UUID MY_UUID=UUID.fromString("00001101-0000-1000-8000-00805FB34FB"); 
protected static final int SUCCESS_CONNECT=0; 
protected static final int MESSAGE_READ=1; 
     Handler mhandler=new Handler(){ 

    @Override 
    public void handleMessage(Message msg) { 
     super.handleMessage(msg); 
     Toast.makeText(getApplicationContext(), "entreing the handler", Toast.LENGTH_LONG).show(); 

     switch (msg.what){ 
    @Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    init(); 
    getpairedDevices(); 



} 

private void startDiscovery() { 

    btAdapter.cancelDiscovery(); 
    btAdapter.startDiscovery(); 
} 



private void init(){ 

    devices=new ArrayList<BluetoothDevice>(); 
    btAdapter=BluetoothAdapter.getDefaultAdapter(); 
    filter=new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    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); 
       devices.add(device); 
       String s=""; 
       for (int a=0;a<pairedDevices.size();a++){ 

        if(device.getName().equals(pairedDevices.get(a))){ 


         //apend 

         s="(Paired)"; 
         break; 
        } 



       } 

       listAdapter.add(device.getName()+"\n"+s+device.getAddress()); 

      } if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action));{ 

       // Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_LONG).show(); 

      } 

      if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){ 
       // Toast.makeText(getApplicationContext(),"state",Toast.LENGTH_LONG).show(); 
      } 

      if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ 
       //Toast.makeText(getApplicationContext(),"finish",Toast.LENGTH_LONG).show(); 



      } 
     } 
    }; registerReceiver(receiver,filter); 
    filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED); 
    registerReceiver(receiver,filter); 

    filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
    registerReceiver(receiver,filter); 

    filter=new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); 
    registerReceiver(receiver,filter); 

    connectNew=(Button)findViewById(R.id.button); 
    listView=(ListView)findViewById(R.id.listView); 
    listAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0); 
    listView.setAdapter(listAdapter); 
    pairedDevices=new ArrayList<String>(); 


    listView.setOnItemClickListener(this); 



} 
@Override 
protected void onPause() { 
    super.onPause(); 
    unregisterReceiver(receiver); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // TODO Auto-generated method stub 
    super.onActivityResult(requestCode, resultCode, data); 
    if(resultCode == RESULT_CANCELED){ 
     Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show(); 
     finish(); 
    } 
} 

private void getpairedDevices(){ 

    deviceArray=btAdapter.getBondedDevices(); 
    if(deviceArray.size()>0){ 

     for(BluetoothDevice device:deviceArray){ 

      pairedDevices.add(device.getName()); 



     } 



    } 
} 

public void TurnOn(View view) { 


    btAdapter.enable(); 




} 


@Override 
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 

    // 

    if (btAdapter.isDiscovering()){ 


     btAdapter.cancelDiscovery(); 

    } 
    if (listAdapter.getItem(arg2).contains("Paired")){ 

@Override 
protected void onPause() { 
    super.onPause(); 
    unregisterReceiver(receiver); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // TODO Auto-generated method stub 
    super.onActivityResult(requestCode, resultCode, data); 
    if(resultCode == RESULT_CANCELED){ 
     Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show(); 
     finish(); 
    } 
} 

private void getpairedDevices(){ 

    deviceArray=btAdapter.getBondedDevices(); 
    if(deviceArray.size()>0){ 

     for(BluetoothDevice device:deviceArray){ 

      pairedDevices.add(device.getName()); 



     } 



    } 
} 

public void TurnOn(View view) { 


    btAdapter.enable(); 




} 


@Override 
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 

    // 

    if (btAdapter.isDiscovering()){ 


     btAdapter.cancelDiscovery(); 

    } 
    if (listAdapter.getItem(arg2).contains("Paired")){ 




      case SUCCESS_CONNECT: 

       String s="hothyfa its a success"; 
       ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg.obj); 
       connectedThread.write(s.getBytes()); 
       Toast.makeText(getApplicationContext(),"Succcssss",Toast.LENGTH_LONG).show(); 

       break; 
      case MESSAGE_READ: 
       byte[] readbuf=(byte[])msg.obj; 
       String s2=new String(readbuf); 
       Toast.makeText(getApplicationContext(),s2,Toast.LENGTH_LONG).show(); 


       break; 
     } 
    } 
}; 
       @Override 
        protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    init(); 
    getpairedDevices(); 



} 

private void startDiscovery() { 

    btAdapter.cancelDiscovery(); 
    btAdapter.startDiscovery(); 
} 



private void init(){ 

    devices=new ArrayList<BluetoothDevice>(); 
    btAdapter=BluetoothAdapter.getDefaultAdapter(); 
    filter=new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    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); 
       devices.add(device); 
       String s=""; 
       for (int a=0;a<pairedDevices.size();a++){ 

        if(device.getName().equals(pairedDevices.get(a))){ 


         //apend 

         s="(Paired)"; 
         break; 
        } 



       } 

       listAdapter.add(device.getName()+"\n"+s+device.getAddress()); 

      } 
      if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action));{ 

       // Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_LONG).show(); 

      } 

      if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){ 
       // Toast.makeText(getApplicationContext(),"state",Toast.LENGTH_LONG).show(); 
      } 

      if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ 
       //Toast.makeText(getApplicationContext(),"finish",Toast.LENGTH_LONG).show(); 



      } 
     } 
    }; 

    registerReceiver(receiver,filter); 
    filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED); 
    registerReceiver(receiver,filter); 

    filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
    registerReceiver(receiver,filter); 

    filter=new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); 
    registerReceiver(receiver,filter); 

    connectNew=(Button)findViewById(R.id.button); 
    listView=(ListView)findViewById(R.id.listView); 
    listAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0); 
    listView.setAdapter(listAdapter); 
    pairedDevices=new ArrayList<String>(); 


    listView.setOnItemClickListener(this); 



} 
       @Override 
       protected void onPause() { 
       super.onPause(); 
       unregisterReceiver(receiver); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // TODO Auto-generated method stub 
    super.onActivityResult(requestCode, resultCode, data); 
    if(resultCode == RESULT_CANCELED){ 
     Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show(); 
     finish(); 
    } 
} 

private void getpairedDevices(){ 

    deviceArray=btAdapter.getBondedDevices(); 
    if(deviceArray.size()>0){ 

     for(BluetoothDevice device:deviceArray){ 

      pairedDevices.add(device.getName()); 



     } 



    } 
} 

public void TurnOn(View view) { 


    btAdapter.enable(); 




} 


@Override 
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 

    // 

    if (btAdapter.isDiscovering()){ 


     btAdapter.cancelDiscovery(); 

    } 
    if (listAdapter.getItem(arg2).contains("Paired")){ 
       BluetoothDevice selectedDevice = devices.get(arg2); 
     ConnectThread connect = new ConnectThread(selectedDevice); 
     connect.start(); 


    } 
    else{ 
     Toast.makeText(getApplicationContext(), "device is not paired", Toast.LENGTH_LONG).show(); 
    } 


} 

public void Discovery(View view) { 

    startDiscovery(); 

} 


      private class ConnectThread extends Thread { 

    private final BluetoothSocket mmSocket; 
    private final BluetoothDevice mmDevice; 

    public ConnectThread(BluetoothDevice device) { 
     // Use a temporary object that is later assigned to mmSocket, 
     // because mmSocket is final 
     BluetoothSocket tmp = null; 
     mmDevice = device; 
     // Log.i(tag, "construct"); 
     // Get a BluetoothSocket to connect with the given BluetoothDevice 
    // Toast.makeText(getApplicationContext(),"client thread is working",Toast.LENGTH_LONG).show(); 
     try { 
      // MY_UUID is the app's UUID string, also used by the server code 
      tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) { 
      // Log.i(tag, "get socket failed"); 


     } 
     mmSocket = tmp; 
    } 

    public void run() { 
     // Cancel discovery because it will slow down the connection 
     btAdapter.cancelDiscovery(); 
     //Log.i(tag, "connect - run"); 
     try { 
      // Connect the device through the socket. This will block 
      // until it succeeds or throws an exception 
      mmSocket.connect(); 
      Log.i(tag, "connect - succeeded"); 
     } catch (IOException connectException) { //Log.i(tag, "connect failed"); 
      // Unable to connect; close the socket and get out 
      try { 
       mmSocket.close(); 
      } catch (IOException closeException) { } 
      return; 
     } 

     // Do work to manage the connection (in a separate thread) 

     // 
     Toast.makeText(getApplicationContext(),"reached the handler",Toast.LENGTH_LONG).show(); 
     mhandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget(); 
    } 





    /** Will cancel an in-progress connection, and close the socket */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { } 
    } 
} 

      private class ConnectedThread extends Thread { 
    private final BluetoothSocket mmSocket; 
    private final InputStream mmInStream; 
    private final OutputStream mmOutStream; 

    public ConnectedThread(BluetoothSocket socket) { 
     mmSocket = socket; 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     Toast.makeText(getApplicationContext(),"Socket Thread is working",Toast.LENGTH_LONG).show(); 
     // Get the input and output streams, using temp objects because 
     // member streams are final 
     try { 
      tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 
     } catch (IOException e) { } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
    } 

    public void run() { 
     byte[] buffer; // buffer store for the stream 
     int bytes; // bytes returned from read() 

     // Keep listening to the InputStream until an exception occurs 
     while (true) { 
      try { 
       // Read from the InputStream 
       buffer = new byte[1024]; 
       bytes = mmInStream.read(buffer); 
       // Send the obtained bytes to the UI activity 
       mhandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
         .sendToTarget(); 

      } catch (IOException e) { 
       break; 
      } 
     } 
    } 

    /* Call this from the main activity to send data to the remote device */ 
    public void write(byte[] bytes) { 
     try { 
      mmOutStream.write(bytes); 
     } catch (IOException e) { } 
    } 

    /* Call this from the main activity to shutdown the connection */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { } 
    } 
} 

,这是布局

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="leen.ibrahim.omar.bsapp.MainActivity"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="BLUETOOTH" 
     android:id="@+id/textView" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Go" 
     android:onClick="Discovery" 
     android:id="@+id/button" 
     android:layout_below="@+id/textView" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" /> 

    <ListView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/listView" 
     android:layout_below="@+id/button" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_marginTop="47dp" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Enaple" 
     android:id="@+id/button2" 
     android:layout_below="@+id/textView" 
     android:onClick="TurnOn" 
     android:layout_centerHorizontal="true" /> 

</RelativeLayout> 

这是什么出现在logcat的

d/BluetoothUtils:isSocketAllowedBySecurityPolicy启动:设备空

w ^/BluetoothAdapter:getBluetoothService()被调用时没有 Bluet oothManagerCallback

d /的BluetoothSocket:连接(),SocketState:INIT,MPFD: {ParcelFileDescriptor:的FileDescriptor [62]}

回答

0

确保你的UUID在客户机代码是作为一个在服务器作为相同码。这个问题可能是因为你目前的UUID。您可以使用下面的服务器代码获取UUID:

TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
String s_uuid = mTelephonyManager.getDeviceId(); 
UUID uuid = UUID.nameUUIDFromBytes(s_uuid.getBytes()); 

不要忘了权限:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>