我是一个总菜鸟。我的目标是通过udp发送传感器数据(陀螺仪磁铁)。另一方面,matlab将接收数据。
此代码应该读取加速度计并显示它,同时它尝试异步地每2000毫秒发送一个预定义的udp数据包。 但它无法运行!有什么建议? 我的代码就像:
public class udp_sensors_matlab extends Activity implements SensorEventListener{
/** Called when the activity is first created. */
SensorManager sensorManager = null;
//for accelerometer values
TextView outputX;
TextView outputY;
TextView outputZ;
String messageStr="test udp";
String ip;
udpOut task;
int server_port = 12345;
DatagramSocket s = null;
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
InetAddress local = null;
DatagramPacket p=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
//just some textviews, for data output
outputX = (TextView) findViewById(R.id.TextView01);
outputY = (TextView) findViewById(R.id.TextView02);
outputZ = (TextView) findViewById(R.id.TextView03);
try {
s = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
local = InetAddress.getByName("81.31.187.32");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
task = new udpOut();
task.execute("g");
timer= new Timer();
timerTask=new TimerTask(){ @Override
public void run() {
// TODO Auto-generated method stub
task = new udpOut();
task.execute("g");
}};
timer.scheduleAtFixedRate(timerTask, 2000, 2000);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onStop() {
super.onStop();
sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
}
synchronized public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()){
case Sensor.TYPE_ACCELEROMETER:
outputX.setText("\tx:"+Float.toString(event.values[0]));
outputY.setText("\ty:"+Float.toString(event.values[1]));
outputZ.setText("\tz:"+Float.toString(event.values[2]));
break;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
class udpOut extends AsyncTask <String, Integer, Long> {
protected Long doInBackground(String... messageStr) {
p = new DatagramPacket(message, msg_length,local,server_port);
try {
s.send(p);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void onProgressUpdate() {
}
}
答案 0 :(得分:1)
我建议您使用调试器逐步调试代码,看看是否能为您提供有关正在/未发生的更具体的信息。当你试图同时做两件事时,你有没有例外?
您还应该使用AlarmManager
而不是TimerTask
。 @CommonsWare在AlarmManager
上有很多好消息,例如:Android: How to use AlarmManager
以下是使用Eclipse调试器的一个教程:http://www.vogella.de/articles/EclipseDebugging/article.html。
根据我使用Android的经验,最好尝试在异常之前设置断点并从那里逐步执行。否则,如果只是在调试器发生时进入调试器,则很难解密异常。