android Java - Textview在活动重启时不附加文本

时间:2014-02-11 11:47:04

标签: java android bluetooth handler thread-synchronization

我一直在尝试在我的应用程序中创建一个功能,包括蓝牙RFID扫描仪,它与我的设备配对,我可以使用它。

我可以接收文本并将其记录在控制台中,当我编译活动时,一切顺利,棒读取代码,然后将文本附加到EditText中,但如果我返回并再次输入活动,我可以看到日志中的代码,但文本没有转到Edittext。

我尝试了很多不同的方法,但似乎没有任何工作:/

这是我的代码:

 /**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bluetooth);


    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> bondedSet = mBluetoothAdapter.getBondedDevices();


    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available.", Toast.LENGTH_LONG).show();

    }

    if (!mBluetoothAdapter.isEnabled()) {
        Toast.makeText(this, "Please enable your BT and re-run this program.", Toast.LENGTH_LONG).show();
        finish();
    }
    if (mBluetoothAdapter.isEnabled()) {
        if(bondedSet.size() == 1){
            for(BluetoothDevice device : bondedSet){
                address = device.getAddress();
                Log.d("bt:", address);
            }
        }
    }
    String address = "00:A0:96:2A:0A:1B";
    out = (EditText) findViewById(R.id.output);

    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    Log.d(TAG, device.getName() + " connected");
    myConnection = new ConnectThread(device);
    myConnection.start();

}
private class ConnectThread extends Thread {
    private final BluetoothSocket mySocket;
    Message msg;

    public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;

        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Log.d(TAG, "CONNECTION IN THREAD DIDNT WORK");
        }
        mySocket = tmp;
    }

    Handler uiThreadHandler = new Handler() {
        public void handleMessage(Message msg) {
            out = (EditText) findViewById(R.id.output);
            Object o = msg.obj;
            out.append(o.toString().trim());
            Log.d("handler", o.toString());
        }
    };

    public void run() {
        out = (EditText) findViewById(R.id.output);

        Log.d(TAG, "STARTING TO CONNECT THE SOCKET");
        setName("My Connection Thread");
        InputStream inStream = null;
        boolean run = false;
        mBluetoothAdapter.cancelDiscovery();

        try {
            mySocket.connect();
            run = true;
        } catch (IOException e) {
            Log.d(TAG, this.getName() + ": CONN DIDNT WORK, Try closing socket");
            try {
                mySocket.close();
                Log.d(TAG, this.getName() + ": CLOSED SOCKET");
            } catch (IOException e1) {
                Log.d(TAG, this.getName() + ": COULD CLOSE SOCKET", e1);
                this.destroy();
            }
            run = false;
        }

        synchronized (BluetoothActivity.this) {
            myConnection = null;
        }

        byte[] buffer = new byte[1024];
        int bytes;
        // handle Connection
        try {
            inStream = mySocket.getInputStream();
            while (run) {
                try {
                    bytes = inStream.read(buffer);
                    readMessage = new String(buffer, 0, bytes);
                    msg = uiThreadHandler.obtainMessage();
                    msg.obj = readMessage;
                    uiThreadHandler.sendMessage(msg);
                    Log.d(TAG, "Received: " + readMessage);
                } catch (IOException e3) {
                    Log.d(TAG, "disconnected");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

2 个答案:

答案 0 :(得分:0)

我的猜测是,这与Thread本身有关。当您第一次启动Activity时,您也可以在.start()上致电Thread,这样可以正常工作。

问题是当您离开Activity并再次打开它时。在这种情况下,会调用onStop()onPause()中的一个(取决于具体情况),之后将分别调用onRestart()onResume()

诀窍现在来了:同时所有这一过程,你的Thread仍在运行。当您显示代码时,它尚未停止/暂停,并一直保持运行。所以基本上我的提示是,你onCreate() Activity方法中的某些内容也应该在你的onPause()onStop()事件以及我的中完成另一个提示它位于ConnectThread(BluetoothDevice device)方法中的某个位置。

要了解如何处理,我首先在onStop()中定义onPause()Activity方法并查看哪个被触发,记录每个属性以查看其值/状态,这样你就可以调试失败的东西了。

There's活动生命周期图。

答案 1 :(得分:0)

问题解决了,代码工作了,TextView得到了输入流,问题是当我离开活动时,线程继续工作,到目前为止,完全没问题,经过TONS小时花了这个,我将TextView变为静态变量并且它可以工作:)

如果有人读到这篇文章,我希望它会有所帮助。