2012-04-02 49 views
2

大家好,这是我的第一个问题。 对不起,如果我犯了任何错误(我无法从我的bluetoothclass代码块中获取代码,我如何解决这个问题没有花费20分钟的时间复制粘贴)蓝牙Android应用程序的问题。初学者

我遇到的问题是可能是Android应用。

这是我的学校的一个项目。我刚刚在2个月前开始学习android。

我已经创建了我自己的类,它是一个蓝牙外壳。 (基本上我学习蓝牙如何工作)。

我有1个活动进行测试,1个名为bluetooh(我的外壳)的类。 有3个线程跟在android开发人员的示例之后。 android bluetooth basics

我们有一个Acceptedthread谁充当服务器。 可以与AcceptedThread建立连接的ConnectThread。 如果他们连接,他们会得到bluetoohsocket。 有了这个bluetoothsocket,两个设备都可以用这个插座启动Connectedthread。 关闭Accapthread和ConnectThread。

我有几个问题。

  1. 我可以建立连接并发送测试消息。但是从1个设备我只能发送3个错误之前。另一台设备可以接收尽可能多的消息(工作)。

2.如果我从设备a发送消息到b /,然后从b发送1到a /它通常不会有效。在它错误并退出应用程序之前。

3.关于如何让事情更好的建议值得欢迎。不要忍住如果我做了一件非常愚蠢的事,就叫我白痴。我对这种编程非常陌生。

以下是代码。

AcceptThread:

public class AcceptThread extends Thread { 
private final BluetoothServerSocket mmServerSocket; 
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); 
private Handler mHandler; 
private Bleutooth BT; 
public AcceptThread(BluetoothAdapter Adapter,Handler handler,Bleutooth bt) { 
    // Use a temporary object that is later assigned to mmServerSocket, 
    // because mmServerSocket is final 
    mHandler = handler; 
    BT = bt; 
    BluetoothServerSocket tmp = null; 
    try { 
     // MY_UUID is the app's UUID string, also used by the client code 
     tmp = Adapter.listenUsingRfcommWithServiceRecord("menno/ruben/app",MY_UUID); 

    } catch (IOException e) { } 
    mmServerSocket = tmp; 
} 

public void run() { 
    Log.d("AcceptThreadlog","Accepthread Run Gestart"); 
    BluetoothSocket socket = null; 
    // Keep listening until exception occurs or a socket is returned 
    while (true) { 
     try { 
      socket = mmServerSocket.accept(); 
     } catch (IOException e) { 
      break; 
     } 
     // If a connection was accepted 
     if (socket != null) { 
      Log.d("AcceptThreadlog","ConnectedThread Gestart"); 
      ConnectedThread mConnectedThread = new ConnectedThread(socket,mHandler); 
      mConnectedThread.start(); 
      BT.HoldConnectThread(mConnectedThread); 
      try { 
       mmServerSocket.close(); 
      } catch (IOException e) { 

       Log.d("AcceptThreadlog","ServerSocket close throwed IOexception"); 
      } 
      break; 
     } 
    } 
} 

/** Will cancel the listening socket, and cause the thread to finish */ 
public void cancel() { 
    try { 
     mmServerSocket.close(); 
    } catch (IOException e) { } 
} 

ConnectThread:

public class ConnectThread extends Thread { 
private final BluetoothSocket mmSocket; 
private final BluetoothDevice mmDevice; 
BluetoothAdapter adapter; 
private Handler mHandler; 
private Bleutooth BT; 
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); 
public ConnectThread(BluetoothDevice device,BluetoothAdapter adapter,Handler handler,Bleutooth bt) { 
    // Use a temporary object that is later assigned to mmSocket, 
    // because mmSocket is final 
    BT = bt; 
    mHandler = handler; 
    BluetoothSocket tmp = null; 
    mmDevice = device; 
    // Get a BluetoothSocket to connect with the given BluetoothDevice 
    try { 
     // MY_UUID is the app's UUID string, also used by the server code 

     tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
    } catch (IOException e) { } 
    mmSocket = tmp; 
} 

public void run() { 
    Log.d("ConnectThread","Run gestart"); 
    // Cancel discovery because it will slow down the connection. 
    if (adapter != null) { adapter.cancelDiscovery();}; 

    try { 
     // Connect the device through the socket. This will block 
     // until it succeeds or throws an exception 
     mmSocket.connect(); 
    } catch (IOException connectException) { 
     // Unable to connect; close the socket and get out 
     try { 
      mmSocket.close(); 
     } catch (IOException closeException) { Log.d("ConnectThread","IOexception opgetreden socket.close"); } 

    } 

    // Do work to manage the connection (in a separate thread) 
    Log.d("ConnectThread","ConnectedThread Gestart"); 
    ConnectedThread mConnectedThread = new ConnectedThread(mmSocket,mHandler); 
    mConnectedThread.start(); 
    BT.HoldConnectThread(mConnectedThread); 
} 

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

ConnectedThread:

public class ConnectedThread extends Thread { 
private final BluetoothSocket mmSocket; 
private final InputStream mmInStream; 
private final OutputStream mmOutStream; 
private Handler mHandler; 
public ConnectedThread(BluetoothSocket socket,Handler handler) 
{ 
    mHandler = handler; 
    mmSocket = socket; 
    InputStream tmpIn = null; 
    OutputStream tmpOut = null; 
    // 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 = new byte[1024]; // buffer store for the stream 
    int bytes; // bytes returned from read() 
    Message message = Message.obtain(mHandler); 
    // Keep listening to the InputStream until an exception occurs 
    // Bevestiging verbinding 
    Log.d("ConnectedThread","YES !!!!!!!!!"); 
    message.what = 1; 
    message.arg1 = 1; 
    mHandler.sendMessage(message); 
    while (true) { 
     try { 

      // Read from the InputStream 
      bytes = mmInStream.read(buffer); 
      message.what = 1; 
      message.arg1 = 2; 
      String Test = new String(buffer); 
      Bundle bundle = new Bundle(); 
      bundle.putString("test",Test); 
      message.setData(bundle); 
      mHandler.sendMessage(message); 

     } catch (IOException e) { 
      break; 
     } 
    } 
} 
    public void write(byte[] bytes) { 
    try { 
     mmOutStream.write(bytes); 
    } catch (IOException e) { } 
} 

public void cancel() { 
    try { 
     mmSocket.close(); 
    } catch (IOException e) { } 
} 

测试活动:

public class BleutoothProftaakActivity extends Activity { 
/** Called when the activity is first created. */ 
    private Bleutooth BT; 
    private Handler mHandler; 
    ConnectedThread Connection = null; 
@Override 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    mHandler = new Handler() { 
     @Override 
synchronized public void handleMessage(Message msg) 
     { 
      if (msg.arg1 == 1 && msg.what == 1) 
      { 
      Toast T = Toast.makeText(getBaseContext(),"Verbinding gemaakt",10000); 
      T.show(); 
      return; 
      } 
      if (msg.arg1 == 2 && msg.what == 1) 
      { 
      Bundle b = msg.getData(); 
      String message = b.getString("test"); 
      Toast T = Toast.makeText(getBaseContext(),message,10000); 
      T.show(); 
      return; 
      } 
     } 


}; 

    BT = new Bleutooth(this); 
    Button button = (Button) findViewById(R.id.button1); 
    button.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v){    
      Toast T = Toast.makeText(getBaseContext(),BT.CheckBleutoothStatus(),10000); 
      T.show(); 
     } 
    }); 
    Button button2 = (Button) findViewById(R.id.button2); 
    button2.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v){    
      BT.TurnBleutoothOn(); 
     } 
    }); 
    Button button3 = (Button) findViewById(R.id.button3); 
    button3.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v) 
     {   
     BT.DiscoverDevices(); 
     } }); 
    Button button9 = (Button) findViewById(R.id.button9); 
    button9.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v){ 
     ArrayList<String> devicesfound = BT.GetFoundDevices(); 
     if (devicesfound.isEmpty()) 
     { 
      Toast T = Toast.makeText(getBaseContext(),"Geen Devices Gevonden",10000); 
      T.show(); 
     } 
     else 
     { 
      for (int i = 0 ;i<devicesfound.size();i++) 
      { 
       Toast T = Toast.makeText(getBaseContext(),devicesfound.get(i),10000); 
       T.show(); 
      } 
     } 
     } 
    }); 
    Button button5 = (Button) findViewById(R.id.button5); 
    button5.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v){    
      ArrayList<String> devicesfound = BT.ReturnBondedDevices(); 
      if (devicesfound.isEmpty()) 
      { 
       Toast T = Toast.makeText(getBaseContext(),"Er zijn geen bonded devices",10000); 
       T.show(); 
      } 
      else 
      { 
       for (int i = 0 ;i<devicesfound.size();i++) 
       { 
        Toast T = Toast.makeText(getBaseContext(),devicesfound.get(i),10000); 
        T.show(); 
       } 
      } 
     } 
    }); 
    Button button6 = (Button) findViewById(R.id.button6); 
    button6.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v){ 
      BT.SetDiscoverable(); 
     } 
    }); 
    Button button7 = (Button) findViewById(R.id.button7); 
    button7.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v){ 
      BT.StartServerSideConnection(mHandler); 
     } 
    }); 
    Button button8 = (Button) findViewById(R.id.button8); 
    button8.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v){ 
      BluetoothAdapter adapter = BT.GetAdapter(); 
      ArrayList<String>devices = BT.ReturnBondedDevices(); 
      BluetoothDevice adress = adapter.getRemoteDevice(devices.get(0)); 
      BT.StartClientSideConnection(adress,mHandler); 
     } 
    }); 
    Button button4 = (Button) findViewById(R.id.button4); 
    button4.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v){ 
      Connection = BT.ReturnConnectedThread(); 
      if (Connection == null) 
      { 
       Toast T = Toast.makeText(getBaseContext(),"Er is geen verbinding",10000); 
       T.show(); 
      } 
      else 
      { 
       String Test = "TESTESTTEST JIppie!!!!!"; 
       byte[] bytearray = Test.getBytes(); 
       Connection.write(bytearray); 
      } 
     } 
    }); 

} 
@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    BT.CleanUp(); 
} 

我的蓝牙等级:

public class Bleutooth 
{ 

BluetoothAdapter adapter; 
Activity main; 
BroadcastReceiver receiver; 
ArrayList<String> founddevices; 
boolean receiverRegistered; 
AcceptThread mAcceptThread= null; 
ConnectThread mConnectThread = null; 
ConnectedThread mConnectedThread = null; 


public Bleutooth(Activity Main) 
{ 
adapter = BluetoothAdapter.getDefaultAdapter(); 
main = Main; 
receiverRegistered = false; 
founddevices = new ArrayList<String>(); 

} 
public BluetoothAdapter GetAdapter(){ 
return adapter; 
} 
public void StartServerSideConnection(Handler handler){ 
// Cancel any thread attempting to make a connection 
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} 

// Cancel any thread currently running a connection 
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} 

// Start the thread to listen on a BluetoothServerSocket 
if (mAcceptThread == null) { 
    mAcceptThread = new AcceptThread(adapter,handler,this); 
    mAcceptThread.start(); 
} 

} 
public void StartClientSideConnection(BluetoothDevice device,Handler handler){ 
//Cancel any thread attempting to make a connection 
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} 

// Cancel any thread currently running a connection 
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} 

// Start the thread to listen on a BluetoothServerSocket 
if (mConnectThread == null) { 
    mConnectThread = new ConnectThread(device,adapter,handler,this); 
    mConnectThread.start(); 
} 

} 
public void SetDiscoverable(){ 
Intent discoverableIntent = 
new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); 
main.startActivity(discoverableIntent); 
} 
public String CheckBleutoothStatus(){ 
String returnString; 
if (adapter == null) 
{ 
returnString = "Geen bleutooth ondersteund"; 
} 
else if(adapter.isEnabled()) 
{ 
    returnString = "Bleutooth staat aan"; 
} 
else 
{ 
    returnString = "Bleutooth staat uit"; 
} 
return returnString; 
} 
public void TurnBleutoothOn(){ 
int REQUEST_ENABLE_BT = 1; 
if (!adapter.isEnabled()) 
{ 
    Intent enableBtIntent = new Intent(adapter.ACTION_REQUEST_ENABLE); 
    main.startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);  
} 
} 

public ArrayList<String> ReturnBondedDevices() { 
ArrayList<String> BondedDevices = new ArrayList<String>(); 
Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices(); 
// If there are paired devices 
if (pairedDevices.size() > 0) { 
    // Loop through paired devices 
    for (BluetoothDevice device : pairedDevices) { 
     // Add the name and address to an array adapter to show in a ListView 
     BondedDevices.add(device.getAddress());   
    } 

} 
return BondedDevices; 
} 
public void DiscoverDevices(){ 
adapter.startDiscovery(); 
// Create a BroadcastReceiver for ACTION_FOUND 
    receiver = new BroadcastReceiver() 
    { 
    public void onReceive(Context context, Intent intent) 
    {   
     String action = intent.getAction(); 
     // When discovery finds a device 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) 
     { 
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

founddevices.add(device.getName() + "\n" + device.getAddress()); 
Toast T = Toast.makeText(main.getBaseContext(),"BleutoothDevice Gevonden",10000); 
      T.show(); 
     } 
    } 
}; 
// Register the BroadcastReceiver 
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
main.registerReceiver(receiver, filter); 
receiverRegistered = true; 
} 
public ArrayList<String> GetFoundDevices(){  
return founddevices;  
} 
public void CleanUp(){ System.gc(); 
if (receiverRegistered) 
{ 
    main.unregisterReceiver(receiver); 
} 
if (mConnectedThread != null) 
{ 
mConnectedThread.cancel(); 
} 
adapter.cancelDiscovery(); 
System.gc(); 
} 
public void HoldConnectThread(ConnectedThread mConnectedThread){ 
this.mConnectedThread = mConnectedThread; 
} 
public ConnectedThread ReturnConnectedThread(){ 
if (this.mConnectedThread != null) 
{ 
    return mConnectedThread; 
} 
else {return null;} 
} 

回答

0

我已经找到答案了。

我一遍又一遍地使用相同的信息。消息并不是那样的。

现在每次创建新消息就像魅力一样修复了问题。

感觉像白痴......