【问题标题】:Android Bluetooth socket connection receiving data in background with AsyncTaskAndroid蓝牙套接字连接在后台使用AsyncTask接收数据
【发布时间】:2015-08-03 10:10:14
【问题描述】:

我是 Android 中的菜鸟,我正在制作一个通过蓝牙将手机与 Arduino 连接的应用程序,当用户按下某些按钮时手机会发送数据,但问题是手机必须期望连续接收数据无需停止应用程序,并且当手机接收数据时必须更新一个listview和两个textview并等待下次接收数据。我已经读过我必须使用一个扩展 AsyncTask 的类,但是在阅读了很多东西之后,我仍然不明白它是如何工作的。在主类中,onCreate 方法执行线程并且会有一些这样的:

ListView listView = (ListView)findViewById(R.id.ListaAlertas);
TextView textTemp = (TextView)findViewById(R.id.NumeroTemperatura);
TextView textHum = (TextView)findViewById(R.id.NumeroHumedad);
Receptor task = new Receptor(listView, textTemp,textHum);
task.execute();

而我读过的类 Receptor 是这样的:

public class Receptor extends AsyncTask<Void, Integer, Void> {

    private WeakReference<ListView> list;
    private WeakReference<TextView> temp;
    private WeakReference<TextView> hum;
    BluetoothSocket socketReceptor;
    InputStream inpReceptor;
    OutputStream outReceptor;

    public Receptor(ListView view, TextView view2, TextView view3) {
        this.list = new WeakReference<ListView>(view);
        this.temp = new WeakReference<TextView>(view2);
        this.hum = new WeakReference<TextView>(view3);
    }

    @Override
    protected Void doInBackground(Void... params) {

        try {
            socketReceptor = SocketSingleton.getSocket();
            inpReceptor = socketReceptor.getInputStream();
            outReceptor = socketReceptor.getOutputStream();

            byte[] buffer = new byte[25];
            int read = inpReceptor.read(buffer);
            while(read != -1){
                publishProgress(read);
                read = inpReceptor.read(buffer);
            }

            inpReceptor.close();
            outReceptor.close();
            socketReceptor.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

我在 SocketSingleton 类中有套接字,现在我只想等待阅读,直到我有东西要接收,然后更新 listView 和属于主类的两个 textView 并再次返回等待阅读,直到我有东西新收到。我不明白 AsyncTask 是如何工作的,所以我需要帮助,对不起我的英语,谢谢。

【问题讨论】:

    标签: java android sockets android-asynctask bluetooth


    【解决方案1】:

    如果您想使用 asynctask 并希望在收到任何数据时更新列表视图,那么您可以在 asynchtask 中使用 publishProgress 方法,我看到您已经在使用它了。

    您可能只需要添加此函数即可接收进度,并在该函数中更新列表视图。

     protected void onProgressUpdate(Integer... progress) {
         //Update the progress on listview
     }
    

    【讨论】:

      【解决方案2】:

      我建议不要为此使用异步任务。它们是短期任务的首选。因为您需要套接字不断侦听数据。

      实现后台服务 https://developer.android.com/training/run-background-service/create-service.html 并使用接收器 https://developer.android.com/reference/android/os/ResultReceiver.html 将数据获取到您的 Activity。

      【讨论】:

        猜你喜欢
        • 2014-03-27
        • 2021-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-08
        • 1970-01-01
        • 2013-12-26
        • 2019-12-11
        相关资源
        最近更新 更多