Android 连续接收传感器输出

Android 连续接收传感器输出,android,android-asynctask,Android,Android Asynctask,我试图从安卓手机控制arduino微控制器。 我需要帮助持续接收来自温度传感器的输出,并将其显示在文本视图上 代码如下: package com.war10ck6001gmail.finalproject; import android.content.Intent; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.AsyncTask; import android.os.

我试图从安卓手机控制arduino微控制器。 我需要帮助持续接收来自温度传感器的输出,并将其显示在文本视图上

代码如下:

package com.war10ck6001gmail.finalproject;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends ActionBarActivity {
    public ToggleButton fan, light, manauto;
    public Button inc, dec;
    public TextView temp;
    public Toolbar mToolbar;
    TCPClient mTcpClient = null;
    public connectTask conctTask = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        // connect to the server

        temp = (TextView) findViewById(R.id.temprature);
        fan = (ToggleButton) findViewById(R.id.fanbutton);
        light = (ToggleButton) findViewById(R.id.lightbutton);
        manauto = (ToggleButton) findViewById(R.id.manauto);
        inc = (Button) findViewById(R.id.increment);
        dec = (Button) findViewById(R.id.decrement);

        Automatic(light);
        Automatic(fan);
        Automatic(inc);
        Automatic(dec);
        conctTask = new connectTask();

        conctTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        mTcpClient = null;

        manauto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Manual(light);
                    Manual(fan);
                    Manual(inc);
                    Manual(dec);
                    mTcpClient.sendMessage("Man");
                }
                else {
                    Automatic(light);
                    Automatic(fan);
                    Automatic(inc);
                    Automatic(dec);
                    mTcpClient.sendMessage("Auto");
                }
            }
        });
        light.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mTcpClient.sendMessage("0");
                }
                else {
                    mTcpClient.sendMessage("1");
                }
            }
        });
        fan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mTcpClient.sendMessage("2");
                }
                else {
                    mTcpClient.sendMessage("3");
                }
            }
        });
        inc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTcpClient.sendMessage("4");

            }
        });
        dec.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTcpClient.sendMessage("5");
            }
        });
    }

    public void Automatic(Button btn) {
        btn.setEnabled(false);
        btn.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
    }

    public void Manual(Button btn) {
        btn.setEnabled(true);
        btn.getBackground().setColorFilter(null);
    }

    public class connectTask extends AsyncTask<String, String, TCPClient> {
        String finalmessage;

        @Override
        protected TCPClient doInBackground(final String... message) {
            //we create a TCPClient object and
            mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {

                @Override
                //here the messageReceived method is implemented
                public void messageReceived(final String message) {

                    try {
                        //this method calls the onProgressUpdate
                        //publishProgress(message);

                        if (message != null) {
                            //finalmessage = message;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    temp.setText(message);
                                }
                            });
                            System.out.println("Return Message from Socket::::: >>>>> " + message);
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            mTcpClient.run();
            if (mTcpClient != null) {
                mTcpClient.sendMessage("Initial Message when connected with Socket Server");
            }

               /* runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        temp.setText(finalmessage);
                    }
                });*/
            return null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            return true;
        }
        if (id == R.id.action_master) {
            return true;
        }
        if (id == R.id.action_bedroom) {
            Intent intent = new Intent(getApplicationContext(), Bedroom.class);
            startActivity(intent);
            return true;
        }
        if (id == R.id.action_Cbedroom) {
            Intent intent = new Intent(getApplicationContext(), Cbedroom.class);
            startActivity(intent);
            return true;
        }
        if (id == R.id.action_diningroom) {
            Intent intent = new Intent(getApplicationContext(), Diningroom.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

“我需要帮助来持续接收…”。的确但是你没有告诉我为什么。你没有告诉我你现在的问题。例如,在调用messageReceived时,您并没有告诉asynctask很早就完成了。我们不知道收到的那个班级成员的消息,因为你没有告诉我们。我们也看不到sendMessage()应该如何工作。这是通过wifi还是蓝牙?嗨,伙计,谢谢你的回复,我想连续地从传感器接收数据。。。请告诉我如何使用套接字实现这一点。。。提前感谢。
我想连续接收来自传感器的数据。
。你以前已经说过了。请不要只重复你自己。你没有对我的评论作出反应。为什么不呢<代码>提前感谢????我现在的问题是,当应用程序启动时,它没有收到arduino发送的数据。。。但在我发送数据后,它开始接收。你认为asynctask每次都会更新textview吗?更新textview的asynctask在哪里?
public class TCPClient {

    public String serverMessage;
    /**
     * Specify the Server Ip Address here. Whereas our Socket Server is started.
     */
    public static final String SERVERIP = "10.5.38.148"; // your computer IP address
    public static final int SERVERPORT = 8888;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    private PrintWriter out = null;
    private BufferedReader in = null;
    MainActivity mainActivity = null;

    /**
     * Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(final OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     *
     * @param message text entered by client
     */
    public void sendMessage(String message) {
        if (out != null && !out.checkError()) {
            System.out.println("message: " + message);
            out.println(message);
            out.flush();
        }
    }


    public void stopClient() {
        mRun = false;
    }

    public void run() {
        mRun = true;
        while (mRun) {
            try {
                //here you must put your computer's IP address.
                InetAddress serverAddr = InetAddress.getByName(SERVERIP);

                Log.e("TCP SI Client", "SI: Connecting...");

                //create a socket to make the connection with the server
                Socket socket = new Socket(serverAddr, SERVERPORT);
                try {
                    //send the message to the server
                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                    Log.e("TCP SI Client", "SI: Sent.");
                    Log.e("TCP SI Client", "SI: Done.");

                    //receive the message which the server sends back
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    //in this while the client listens for the messages sent by the server

                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);

                        Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
                    }
                    serverMessage = null;
                }
                catch (Exception e) {
                    Log.e("TCP SI Error", "SI: Error", e);
                    e.printStackTrace();
                }
                finally {
                    //the socket must be closed. It is not possible to reconnect to this socket
                    // after it is closed, which means a new socket instance has to be created.
                    socket.close();
                }
            }
            catch (Exception e) {
                Log.e("TCP SI Error", "SI: Error", e);
            }
        }
    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}