Android 安卓可以';重新打开应用程序后,请不要连接到NXT

Android 安卓可以';重新打开应用程序后,请不要连接到NXT,android,bluetooth,nxt,reconnect,Android,Bluetooth,Nxt,Reconnect,首先,我的英语不是很好,但我希望你能理解我的问题:) 所以,我是新来的,在安卓也是新来的。我有两部手机:摩托罗拉Defy(带Cyanogenmond-Android 4.4.2)和索尼Xperia J(Android 4.1.2-not root)。 我已经创建了一个应用程序,可以通过蓝牙将手机与乐高Mindstorm NXT连接起来。第一次,它在Xperia J上工作得非常好。它连接到NXT,当我关闭NXT时,手机试图重新连接。它似乎在工作,但我关闭了应用程序,并重新打开了一些时间。之后,Xp

首先,我的英语不是很好,但我希望你能理解我的问题:) 所以,我是新来的,在安卓也是新来的。我有两部手机:摩托罗拉Defy(带Cyanogenmond-Android 4.4.2)和索尼Xperia J(Android 4.1.2-not root)。 我已经创建了一个应用程序,可以通过蓝牙将手机与乐高Mindstorm NXT连接起来。第一次,它在Xperia J上工作得非常好。它连接到NXT,当我关闭NXT时,手机试图重新连接。它似乎在工作,但我关闭了应用程序,并重新打开了一些时间。之后,Xperia J无法连接到NXT,但我不知道为什么?我试图删除所有存储数据(因为SharedReferences),但也没有成功。然后我重新启动了手机,它似乎又完美地连接起来了。 我以为我编码错了,但在另一部电话上没有问题。 有人能帮我吗有什么问题吗?(我是一名学生,所以如果有人知道如何重新连接NXT,那么请告诉我:D)


主要活动:

public class MainActivity extends ActionBarActivity {

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what) {
            case BTCommunicator.DATA_RECEIVED:
                byte[] readBuf = (byte[]) msg.obj;
                String readMessage = new String(readBuf, 0, msg.arg1);
                break;
            case BTCommunicator.CONNECTION_SUCCESSFULL:
                Toast.makeText(MainActivity.this, "Successful connection", Toast.LENGTH_LONG).show();
                BTCommunicator.getInstance().start();
                break;
            case BTCommunicator.CONNECTION_FAILED:
                Toast.makeText(MainActivity.this, "Connection failed", Toast.LENGTH_SHORT).show();
                try {
                    Thread.sleep(2000);
                } catch (Exception ex) {}
                BTCommunicator.getInstance().cancel();
                connectToDevice();
                break;
            case BTCommunicator.CONNECTION_CLOSED:
                Toast.makeText(MainActivity.this, "Connection closed", Toast.LENGTH_SHORT).show();
                BTCommunicator.getInstance().cancel();
                connectToDevice();
                break;
        }
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onPause() {
    BTCommunicator.getInstance().cancel();
    super.onPause();
}

public void allConnection(View v) {
    connectToDevice();
}

public void connectToDevice() {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
   String btAddress = sharedPreferences.getString(DeviceFounder.KEYBTADDRESS, "");
    String selectedUUID = sharedPreferences.getString(DeviceFounder.KEYUUID, "");


    Set<BluetoothDevice> pairedDevices = BTCommunicator.getInstance().getBluetoothAdapter().getBondedDevices();
    boolean deviceFound = false;
    for(BluetoothDevice device : pairedDevices) {
        if(device.getAddress().equals(btAddress)) {
            new BTConnectAsyncTask(
                     this, handler, device, selectedUUID).execute();
            deviceFound = true;
        }
    }

    if(!deviceFound) {
        Toast.makeText(this, "Device is not paired: " + btAddress, Toast.LENGTH_LONG).show();
    }
}

public void showDeviceFounder(View v) {
    startActivity(new Intent(this, DeviceFounder.class));
}
最后是BTCommunicator类:

'public class BTCommunicator extends Thread {
public static final int DATA_RECEIVED = 0;
public static final int CONNECTION_SUCCESSFULL = 1;
public static final int CONNECTION_FAILED = 2;
public static final int CONNECTION_CLOSED = 3;

//Ez reprezentálja a fizikai BlueTooth adaptert. Ezt használva
//tudod felfedni a többi eszközt MAC-kel és BlueToothServerSocket
//segítségével figyelni a bejövő kommunikációt!
private BluetoothAdapter bluetoothAdapter = null;
//Ezen keresztül engedi a rendszer, hogy egy app kommunikáljon egy
//másik appal. Input- és OutputStreamen keresztül.
private InputStream inStream = null;
private OutputStream outStream = null;
private Handler msgHandler = null;
private static boolean enabled = false;
public static  BluetoothSocket clientSocket = null;

//statikus példány kérése
private static BTCommunicator instance = null;

public static BTCommunicator getInstance() {
    if(instance == null) {
        instance = new BTCommunicator();
    }
    return instance;
}

protected BTCommunicator() {
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}

public BluetoothAdapter getBluetoothAdapter() {
    return bluetoothAdapter;
}

public void connect(BluetoothDevice device, UUID uuid, Handler
        handler)
{
    bluetoothAdapter.cancelDiscovery();
    msgHandler = handler;
    enabled = true;

    try {
        clientSocket = device.createRfcommSocketToServiceRecord(uuid);
        clientSocket.connect();
        inStream = clientSocket.getInputStream();
        outStream = clientSocket.getOutputStream();
        handler.obtainMessage(CONNECTION_SUCCESSFULL,
                "").sendToTarget();
    } catch (Exception e) {
        Log.e("BTCommunicator", e.getMessage());
        try {
            handler.obtainMessage(CONNECTION_FAILED, e.getMessage
                    ()).sendToTarget();
            clientSocket.close();
           // BTCommunicator.getInstance().cancel();
            //BTCommunicator.getInstance().connect(device, uuid, handler);
        } catch (IOException closeException) { }
    }
}

public void run() {
    byte[] buffer = new byte[1024];
    int bytes;

    while (enabled) {
        try {
            bytes = inStream.read(buffer);
            msgHandler.obtainMessage(DATA_RECEIVED, bytes, -1,
                    buffer).sendToTarget();
        } catch (IOException e) {
            msgHandler.obtainMessage(CONNECTION_CLOSED,
                    "").sendToTarget();

            try {
                clientSocket.close();
            } catch (IOException e2) { }
            break;
        }
    }
}

public void write(byte[] bytes) {
    try {
        if(outStream != null) {
            outStream.write(bytes);
        }
    } catch (IOException e) {
        Log.e("BTCOMM", e.getMessage());
    }
}

public void cancel() {
    enabled = false;

    if (bluetoothAdapter != null)
        bluetoothAdapter.cancelDiscovery();

    if (msgHandler != null)
        /*msgHandler.obtainMessage(CONNECTION_CLOSED,
                "").sendToTarget();*/

    if (outStream != null) {
        try {
            outStream.close();
            outStream = null;
        } catch (Exception e) {
        }
    }

    if (inStream != null) {
        try {
            inStream.close();
            inStream = null;
        } catch (Exception e) {
        }
    }

    if (clientSocket != null) {
        try {
            clientSocket.close();
            clientSocket = null;
        } catch (IOException e) {
        }
    }

    instance = null;
}
} `

好的,问题解决了:)我应该调用BTCommunicator catch块中的整个cancel函数,因为如果我关闭程序,Android 4.1.2将不会关闭流。我不知道为什么,可能是操作系统中的错误?XD,因为它只是在Android版本4.4.2之前引起的

 try {
        UUID serviceUuid = UUID.fromString(selectedUUID);
        BTCommunicator.getInstance().connect(device, serviceUuid, handlerStatus);
        return "OK";
    } catch (Exception e) {
        return ("Error: "+e.getMessage());
    }
'public class BTCommunicator extends Thread {
public static final int DATA_RECEIVED = 0;
public static final int CONNECTION_SUCCESSFULL = 1;
public static final int CONNECTION_FAILED = 2;
public static final int CONNECTION_CLOSED = 3;

//Ez reprezentálja a fizikai BlueTooth adaptert. Ezt használva
//tudod felfedni a többi eszközt MAC-kel és BlueToothServerSocket
//segítségével figyelni a bejövő kommunikációt!
private BluetoothAdapter bluetoothAdapter = null;
//Ezen keresztül engedi a rendszer, hogy egy app kommunikáljon egy
//másik appal. Input- és OutputStreamen keresztül.
private InputStream inStream = null;
private OutputStream outStream = null;
private Handler msgHandler = null;
private static boolean enabled = false;
public static  BluetoothSocket clientSocket = null;

//statikus példány kérése
private static BTCommunicator instance = null;

public static BTCommunicator getInstance() {
    if(instance == null) {
        instance = new BTCommunicator();
    }
    return instance;
}

protected BTCommunicator() {
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}

public BluetoothAdapter getBluetoothAdapter() {
    return bluetoothAdapter;
}

public void connect(BluetoothDevice device, UUID uuid, Handler
        handler)
{
    bluetoothAdapter.cancelDiscovery();
    msgHandler = handler;
    enabled = true;

    try {
        clientSocket = device.createRfcommSocketToServiceRecord(uuid);
        clientSocket.connect();
        inStream = clientSocket.getInputStream();
        outStream = clientSocket.getOutputStream();
        handler.obtainMessage(CONNECTION_SUCCESSFULL,
                "").sendToTarget();
    } catch (Exception e) {
        Log.e("BTCommunicator", e.getMessage());
        try {
            handler.obtainMessage(CONNECTION_FAILED, e.getMessage
                    ()).sendToTarget();
            clientSocket.close();
           // BTCommunicator.getInstance().cancel();
            //BTCommunicator.getInstance().connect(device, uuid, handler);
        } catch (IOException closeException) { }
    }
}

public void run() {
    byte[] buffer = new byte[1024];
    int bytes;

    while (enabled) {
        try {
            bytes = inStream.read(buffer);
            msgHandler.obtainMessage(DATA_RECEIVED, bytes, -1,
                    buffer).sendToTarget();
        } catch (IOException e) {
            msgHandler.obtainMessage(CONNECTION_CLOSED,
                    "").sendToTarget();

            try {
                clientSocket.close();
            } catch (IOException e2) { }
            break;
        }
    }
}

public void write(byte[] bytes) {
    try {
        if(outStream != null) {
            outStream.write(bytes);
        }
    } catch (IOException e) {
        Log.e("BTCOMM", e.getMessage());
    }
}

public void cancel() {
    enabled = false;

    if (bluetoothAdapter != null)
        bluetoothAdapter.cancelDiscovery();

    if (msgHandler != null)
        /*msgHandler.obtainMessage(CONNECTION_CLOSED,
                "").sendToTarget();*/

    if (outStream != null) {
        try {
            outStream.close();
            outStream = null;
        } catch (Exception e) {
        }
    }

    if (inStream != null) {
        try {
            inStream.close();
            inStream = null;
        } catch (Exception e) {
        }
    }

    if (clientSocket != null) {
        try {
            clientSocket.close();
            clientSocket = null;
        } catch (IOException e) {
        }
    }

    instance = null;
}