bluetooth android force关闭

问题描述:

我试图从我的android连接到我的笔记本电脑上的蓝牙服务器,但是我的app force关闭了。我也包含了蓝牙权限。有人可以检查代码并告诉我我可能会做错什么吗?bluetooth android force关闭

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; 
    } 

    } 

我看到的第一件事就是你正在尝试使用socket.connect(),即使套接字分配抛出异常。

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; 

}