为什么XMPP不能与蓝牙同时工作?

时间:2012-04-12 14:22:05

标签: android bluetooth xmpp

我编写了一个Android应用程序,作为通过XMPP和蓝牙进行通信的网络中间层。出于某种原因,我发现尽管蓝牙连接和XMPP连接在我将它们组合在同一个应用程序中时似乎单独工作,但蓝牙连接似乎会中断XMPP连接并且应用程序失败。有没有人遇到过这样的问题,或者在我的代码中发现可能导致此问题的问题?

注意我已从代码中删除了我的IP地址。

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class XMPPActivity extends Activity {
    private static final int REQUEST_ENABLE_BT = 1;
    private BluetoothAdapter mBluetoothAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Thread th = new Thread(new XMPP());
        //th.start();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
        mBluetoothAdapter.startDiscovery();
        try {
            Thread.sleep(12000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        /*mBluetoothAdapter.cancelDiscovery();
        unregisterReceiver(mReceiver);*/
    }
    final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Add the name and address to an array adapter to show in a ListView
                System.out.println(device.getName() + "\n" + device.getAddress());
                if(device.getName().contentEquals("NXT")){
                    Thread connection = new Thread(new ConnectThread(device,mBluetoothAdapter));
                    connection.start();
                }
            }
        }
    };
}

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
public class XMPPClient {
    private String server;
    private int port;
    private ConnectionConfiguration config;
    private XMPPConnection connection;
    private PacketListener messageListener;
    private PacketFilter messageFilter;
    public XMPPClient(String server, int port){
        this.server=server;
        this.port = port;
    }
    public void init() throws XMPPException {
        config = new ConnectionConfiguration(server,port);
        config.setSASLAuthenticationEnabled(false);
        config.setSecurityMode(SecurityMode.disabled);

        connection = new XMPPConnection(config);
        connection.connect();
        messageListener = new MyMessageListener();
        messageFilter = new MessageTypeFilter(Message.Type.chat);
        connection.addPacketListener(messageListener,messageFilter);
    }
    public void performLogin(String username, String password) throws XMPPException{
        if(connection!=null&&connection.isConnected()){
            connection.login(username, password);
        }
    }
    public void destroy(){
        if(connection!=null && connection.isConnected()){
            connection.disconnect();
        }
    }
    public void sendMessage (String message, String buddyJID) throws XMPPException{
        System.out.println(String.format("Sending message '%1$s' with name %2$s", message, buddyJID));
        Message msg = new Message(buddyJID,Message.Type.chat);
        msg.setBody(message);
        this.connection.sendPacket(msg);
    }
    public void createEntry (String user, String name) throws Exception {
        System.out.println(String.format("Creating entry for buddy '%1$s' to user %2$s", user,name));
        Roster roster = connection.getRoster();
        roster.createEntry(user, name, null);
    }
    class MyMessageListener implements PacketListener{
        public void processPacket(Packet packet) {
            if(!(packet instanceof Message))
                return;
            // Extract the useful stuff
            Message message = (Message)packet;
            String from = message.getFrom();
            String body = message.getBody();
            System.out.println(String.format("Recieved message '%1$s' from %2$s", body,from));
        }
    }
}


import org.jivesoftware.smack.XMPPException;

public class XMPP implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        String username = "androidtestuser1";
        String password = "androidtestuser1";
        XMPPClient xmppClient = new XMPPClient("ipAddress",5222);
        try {
            xmppClient.init();
        } catch (XMPPException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            xmppClient.performLogin(username, password);
        } catch (XMPPException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            xmppClient.sendMessage("Hello mate", "testuser1@localhostname/Spark 2.6.3");
        } catch (XMPPException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        boolean isRunning = true;
        while (isRunning){
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        xmppClient.destroy();
    }

}

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

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

public class ConnectThread extends Thread {
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private final BluetoothSocket mmSocket;
    private final BluetoothAdapter mBluetoothAdapter;

    public ConnectThread(BluetoothDevice device, BluetoothAdapter mBluetoothAdapter) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        // 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;
        this.mBluetoothAdapter = mBluetoothAdapter;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();
        System.out.println("connecting");
        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) { }
            return;
        }
        System.out.println("connected");
        byte b = 1;
        try {
            writeMessage(b);
        } catch (InterruptedException e) {
            System.out.println("Send failed");
        }
        // Do work to manage the connection (in a separate thread)
        //manageConnectedSocket(mmSocket);
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
    public void writeMessage(byte msg) throws InterruptedException{
        if(mmSocket!=null){
            try {

                OutputStreamWriter out=new OutputStreamWriter(mmSocket.getOutputStream());
                out.write(msg);
                out.flush();

                Thread.sleep(1000);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            //Error
        }
    }
}

0 个答案:

没有答案