0

現在、Bluetooth ソケットからデータを読み取る必要がある Android アプリケーションに取り組んでいます。私が使用しているコードは次のとおりです。

runOnUiThread(new Runnable() {
    public void run()
    {
        try{
            ReadData();
    }catch(Exception ex){}
    }
});
public void ReadData() throws Exception{
    try {
        b1 = new StringBuilder();
        stream = socket.getInputStream();
        int intch;
        String output = null;
        String k2 = null;
        byte[] data = new byte[10];
        // read data from input stream if the end has not been reached
        while ((intch = stream.read()) != -1) {
            byte ch = (byte) intch;
            b1.append(ByteToHexString(ch) +"/");
            k++;
            if(k == 20) // break the loop and display the output
            {
                output = decoder.Decode(b1.toString());
                textView.setText(output);
                k=0;
                break;
            }
        }
        // close the input stream, reader and socket
        if (stream != null) {
            try {stream.close();} catch (Exception e) {}
            stream = null;
        }
        if (socket != null) {
            try {socket.close();} catch (Exception e) {}
            socket = null;
        }
    } catch (Exception e) {
    }
}

ただし、Android デバイスでアプリケーションを実行すると、UI が自動的に更新されず、フリーズし続けます。UI フリーズの問題を解決する方法を知っている人はいますか? ループ終了後にデータを表示するのではなく、動的にUIにデータを表示したい。

事前にご協力いただきありがとうございます。

よろしく、

チャールズ

4

3 に答える 3

1

JavaInputStream.read()言う

このメソッドは、入力データが利用可能になるまでブロックします

UIスレッドのソケットから読み取っているため、UIがブロックされています。ソケットからデータを読み取り、動的更新のために結果をUIに渡す別のスレッドが確実に必要です。

于 2012-06-24T16:21:03.743 に答える
0

非UIスレッドでReadData()メソッドを実行する必要があります。データが利用可能になったら、runOnUIthreadメカニズムを使用して、UIスレッドで結果として生じるtextViewの更新のみを実行します。

于 2012-06-24T16:36:24.440 に答える
0

これを試して、

使い方。

1. When Android Application starts you are on the UI Thread. Doing any Process intensive work on this thread will make your UI unresponsive.

2. Its always advice to keep UI work on UI Thread and Non-UI work on Non-UI Thread. But from HoneyComb version in android it became a law.

コードの問題は何ですか。

1. You are reading the data on the UI thread, making it wait to finish reading.. here in this line...while((intch = stream.read())!= -1))。

それを解決する方法:

1. Use a separate Non-UI thread, and to put the value back to the UI thread use Handler.

2. Use the Handler class. Handler creates a reference to the thread on which it was created. This will help you put the work done on the Non-UI thread back on the UI thread.

3. Or use AsyncTask provided in android to Synchronize the UI and Non-UI work,which does work in a separate thread and post it on UI.

于 2012-06-24T16:39:53.393 に答える