我试图通过tcp套接字来读取加速度计值并通过它传输它。 此代码可以读取加速度计值并可以通过tcp进行通信,但我无法通过tcp套接字发送加速度计值。
这是Stream.java(活动)
TextView textView;
//String SIP="10.118.33.132";
int SP=5000;
float ay;
String TAG="main";
private SensorManager sensorManager;
GetAccVal myval = new GetAccVal();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream);
textView = (TextView) findViewById(R.id.textView1);
Bundle extra = getIntent().getExtras();
String SIP = extra.getString("SIP_1");
Log.d(TAG,"SIP1 ex:"+SIP);
Runnable ConnectClient = new Client(SIP);
new Thread(ConnectClient).start();
textView.setText("Thread Started");
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
// add listener. The listener will be HelloAndroid (this) class
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
ay=event.values[1];
// textView.setText("y="+ay);
myval.setVal(ay);
// Log.d(TAG,"Sensor X=:"+ay);
// String sn = myval.getsen();
textView.setText("y="+ay);
}
}
}
Client.java
public class Client implements Runnable {
String SIP_1;
int SP=5000;
Socket s;
int a=0;
boolean SF=false;
String TAG = "Connection";
PrintWriter out;
public Client(String SIP_1) {
this.SIP_1=SIP_1;
}
public void run() {
GetAccVal myval = new GetAccVal();
myval.setip(SIP_1);
}
}
GetAccVal.java
public class GetAccVal {
public float y,y1,my;
String ecosen,ip;
String TAG="DATA";
boolean connected=false;
public void setVal(float y){
this.y=y;
if(connected){
try{
Log.d(TAG,"setval y=:"+y);
Log.d(TAG,""+y);
out.println(y);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void setip(String ip){
this.ip=ip;
Log.d(TAG,"ip= :"+ip);
try{
InetAddress serverAddr = InetAddress.getByName(ip);
s = new Socket(serverAddr, SP);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(s.getOutputStream())),
true);
connected=true;
}
catch (UnknownHostException e1) {
e1.printStackTrace();
Log.d(TAG,"EXIT ex:"+e1);
} catch (IOException e1) {
e1.printStackTrace();
Log.d(TAG,"EXIT ex:"+e1);
}
}
}