0

我正在编写一个连接到蓝牙设备的 Android 应用程序,读取从设备发送的数据,将其添加到AChartEngine图表,并在 TextView 中显示数据。

我的蓝牙代码与 BluetoothChat 示例代码中的线程实现非常相似(它与 SDK 一起提供)。我可以在 LogCat 中看到ConnectedThread循环正在执行并因此获取新数据,但是我的 TextView 在 7 行后停止更新,并且图形间歇性地暂停(更不用说它只是间歇性地响应交互)。LogCat 中没有显示任何错误。此外,如果我删除图表,TextView 的问题仍然存在。

为什么从我的其他线程更新时我的 UI 线程不工作?


以下是我的代码的相关部分。通过蓝牙发送的每个字符串都被接收ConnectedThread并发送到BluetoothController.addToGraph(),然后NewPoints AsyncTaskviewer类中运行。

private class ConnectedThread extends Thread {
    public ConnectedThread(BluetoothSocket socket, String socketType) { ... } // Initialize input and output streams here

    public void run() {
        while (true) {
            Log.i(TAG, "READ mConnectedThread");
            // Read from the InputStream
            byte[] buffer = new byte[1024];
            bytes = mmInStream.read(buffer);

            // Send the obtained bytes to the UI Activity
            mHandler.obtainMessage(BluetoothController.MESSAGE_READ, bytes, -1, buffer)
                    .sendToTarget();
            Log.i(TAG, "LOOPEND mConnectedThread");
        }
    }
}
public class BluetoothController extends Activity {
    private viewer plotter;
    public static final int MESSAGE_READ = 2;
    // The Handler that gets information back from the BluetoothClass
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    String readMessage = new String(readBuf, 0, msg.arg1);
                    addToGraph(readMessage);
                    break;
            }
        }
    };

    protected void addToGraph(String result) {
        // process the string, create doubles x and y that correspond to a point (x,y)
        plotter.new NewPoints().execute(x, y);
    }
}
public class viewer extends Activity {
    // initialize graph, etc.

    @Override
    protected void onResume() {
        // Create handlers for textview
        textHandler = new Handler();

        // Set scrolling for textview
        myTextView.setMovementMethod(new ScrollingMovementMethod());

    protected class NewPoints extends AsyncTask<Double, Void, Void> {
        @Override
        protected Void doInBackground(Double... values) {
            mCurrentSeries.add(values[0], values[1]); // x, y

            if (mChartView != null) {
                mChartView.repaint();
            }

            final Double[] messages = values;
            textHandler.post(new Runnable() {
                @Override
                public void run() {
                    myTextView.append("(" + messages[0].toString() + ", " + messages[1].toString() + ") \n");
                }
            });

            return null;
        }
    }
}

是什么赋予了?如果需要更多代码,请告诉我。

4

3 回答 3

2

对我来说似乎倒退了......您的 AsyncTask 正在更新您的 textview 和 currentseries,但 AsyncTask 应该用于长时间运行的任务,例如与其他设备/网络通信。您的 UI 线程应该正在更新文本视图,而您却以相反的方式得到了它

doInBackground 应该包含与您的蓝牙设备对话的代码

于 2012-08-01T00:50:33.360 回答
1

当然,这里有一个来自 Dropbox api,它展示了如何在您的任务在后台进行通信工作时实现进度条。您必须为自己的邪恶目的修改它,但它是后台任务的一个很好的例子。

 /**
 * Here we show uploading a file in a background thread, trying to show
 * typical exception handling and flow of control for an app that uploads a
 * file
 */
public class UploadFile extends AsyncTask<Void, Long, Boolean> {

    private DropboxAPI<?> mApi;
    private File mFile;

    private long mFileLen;
    private UploadRequest mRequest;
    private Context mContext;
    private final ProgressDialog mDialog;

    private String mErrorMsg;



public UploadFile(Context context, DropboxAPI<?> api, File file) {
    // We set the context this way so we don't accidentally leak activities
    mContext = context.getApplicationContext();

    mFileLen = file.length();
    mApi = api;
    mFile = file;

    mDialog = new ProgressDialog(context);
    mDialog.setMax(100);
    mDialog.setMessage("Uploading " + file.getName());
    mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mDialog.setProgress(0);
    mDialog.setButton(Dialog.BUTTON_POSITIVE ,(CharSequence) "Cancel", new Dialog.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // This will cancel the putFile operation
            mRequest.abort();
        }
    });
    mDialog.show();
}

@Override
protected Boolean doInBackground(Void... params) {
    try {
        // By creating a request, we get a handle to the putFile operation,
        // so we can cancel it later if we want to
        FileInputStream fis = new FileInputStream(mFile);
        String path = mFile.getName();
        mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
                new ProgressListener() {
            @Override
            public long progressInterval() {
                // Update the progress bar every half-second or so
                return 500;
            }

            @Override
            public void onProgress(long bytes, long total) {
                publishProgress(bytes);
            }
        });

        if (mRequest != null) {
            mRequest.upload();
            return true;
        }

    } catch (DropboxUnlinkedException e) {
        // This session wasn't authenticated properly or user unlinked
        mErrorMsg = "This app wasn't authenticated properly.";
    } catch (DropboxFileSizeException e) {
        // File size too big to upload via the API
        mErrorMsg = "This file is too big to upload";
    } catch (DropboxPartialFileException e) {
        // We canceled the operation
        mErrorMsg = "Upload canceled";
    } catch (DropboxServerException e) {
        // Server-side exception.  These are examples of what could happen,
        // but we don't do anything special with them here.
        if (e.error == DropboxServerException._401_UNAUTHORIZED) {
            // Unauthorized, so we should unlink them.  You may want to
            // automatically log the user out in this case.
        } else if (e.error == DropboxServerException._403_FORBIDDEN) {
            // Not allowed to access this
        } else if (e.error == DropboxServerException._404_NOT_FOUND) {
            // path not found (or if it was the thumbnail, can't be
            // thumbnailed)
        } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
            // user is over quota
        } else {
            // Something else
        }
        // This gets the Dropbox error, translated into the user's language
        mErrorMsg = e.body.userError;
        if (mErrorMsg == null) {
            mErrorMsg = e.body.error;
        }
    } catch (DropboxIOException e) {
        // Happens all the time, probably want to retry automatically.
        mErrorMsg = "Network error.  Try again.";
    } catch (DropboxParseException e) {
        // Probably due to Dropbox server restarting, should retry
        mErrorMsg = "Dropbox error.  Try again.";
    } catch (DropboxException e) {
        // Unknown error
        mErrorMsg = "Unknown error.  Try again.";
    } catch (FileNotFoundException e) {
    }
    return false;
}

@Override
protected void onProgressUpdate(Long... progress) {
    int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
    mDialog.setProgress(percent);
}

@Override
protected void onPostExecute(Boolean result) {
    mDialog.dismiss();
    if (result) {
        showToast("File successfully uploaded");
    } else {
        showToast(mErrorMsg);
    }
}
于 2012-08-01T14:59:03.173 回答
0

我也在使用 achartengine 和 AsynkTask 编写一个类似的应用程序。您应该在 doInBackground 中管理蓝牙,并在收到新数据时调用 publishProgress 以在 onProgressUpdate 方法上更新您的 UI(TextView 和 Achartengine)。doInBackground 永远不应该更新 UI,奇怪的是它实际上对你有用!如果您正在绘制具有“低”刷新率的实时数据,那将是可行的。如果不是,我建议将蓝牙部分实现为服务并将您的数据广播到管理和更新 UI 的活动。如果您收到大量数据,您会发现通过广播发送数据会限制您的吞吐量,因为您必须将数据类设为 Parcelable,这非常慢,并且您很快就会遇到 Android 的 binder 架构的限制,该架构用于“Localmanager.

如果您打算使用 achartengine 进行快速实时绘图,您应该首先检查我的问题之一,关于您稍后会发现的问题:achartengine 准备好进行实时绘图了吗?

于 2013-01-09T20:10:16.003 回答