【发布时间】:2016-01-27 15:19:03
【问题描述】:
我正在尝试使用 asynctask onprogress 更新方法将传感器数据从 arduino 获取到 Android 手机。传感器的数据显示在TextView 中,并且有 2 个用于打开和关闭 LED 的按钮。
问题是 android 手机正在从 arduino 获取实时数据,但我无法同时打开和关闭灯。我试图阻止安卓手机获取传感器的数据并试图打开和关闭灯。这是有效的。获取传感器数据和打开/关闭 LED 都不能同时工作。有人可以帮我解决这个问题。这对我来说非常重要,因为我将它用于项目。
安卓代码:
package com.example.arduinoandroidasyntasktesting6;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView data;
Button On,Off;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Sensors().execute("");
data=(TextView)findViewById(R.id.textView2);
On=(Button)findViewById(R.id.buttonOn2);
Off=(Button)findViewById(R.id.buttonOff2);
On.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
new Sensors().execute("?led2=1");
}
});
Off.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
new Sensors().execute("?led2=0");
}
});
}
class Sensors extends AsyncTask<String, byte[], String>{
InputStream nis;
OutputStream nos;
BufferedReader in;
DefaultHttpClient httpclient =new DefaultHttpClient();
URL url;
URLConnection urlconn=null;
InputStreamReader isn;
@Override
protected String doInBackground(String... params) {
try{
while(true){
url =new URL("http://192.168.1.177/"+params[0]);
urlconn=(HttpURLConnection)url.openConnection();
nis = urlconn.getInputStream();
in= new BufferedReader(new InputStreamReader(nis));
String msg = in.readLine();
byte[] thebyte =msg.getBytes();
publishProgress(thebyte);
}
}
catch(IOException e)
{
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(byte[]... values) {
String command=new String(values[0]);//get the String from the recieved bytes
data.setText(command);
}
}
}
【问题讨论】:
标签: android http android-asynctask httpurlconnection async-onprogressupdate