0

I'm trying to connect to a Bluetooth server on my laptop from my android, but my app force closes.I have included the Bluetooth permissions too. Can somebody please check the code and tell me what I might be doing wrong?

   package com.android.example.blueoga;

   import java.io.IOException;
   import java.util.UUID;

   import android.os.Bundle;
   import android.app.Activity;
   import android.bluetooth.BluetoothAdapter;
   import android.bluetooth.BluetoothDevice;
   import android.bluetooth.BluetoothSocket;
   import android.content.Intent;
   import android.view.Menu;
   import android.widget.TextView;

   public class BlueGOA extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView view=(TextView)findViewById(R.id.textView1);
    BluetoothSocket socket;
    socket=null;
    String address="64:27:37:D0:1F:48";
    UUID MY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    int REQUEST_ENABLE_BT=1;
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        // Device does not support Bluetooth
        view.setText("Go Home Suckers");
    }
    else if(!mBluetoothAdapter.isEnabled()){
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);




    }
    BluetoothDevice device=mBluetoothAdapter.getRemoteDevice(address);
    try{
        socket=device.createRfcommSocketToServiceRecord(MY_UUID);
    }catch(IOException e){
        view.setText("problem in socket sucker");
    }
    try {
        socket.connect();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        view.setText("Problem in connecting sucker");
    }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.blue_go, menu);
    return true;
    }

   }
4

2 回答 2

0

我看到的第一件事是即使套接字分配引发异常,您也正在尝试使用 socket.connect() 。

于 2013-02-22T17:53:38.553 回答
0
public class BlueGOA extends Activity {

    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmdevice;
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    mmdevice = device;
    BluetoothSocket tmp = null;
    // Get a BluetoothSocket to connect with the given BluetoothDevice
    try {
         tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) { }
    mmSocket = tmp;

}

于 2013-02-22T17:59:18.383 回答