我对安卓很陌生。我想构建客户端/服务器应用程序,其中客户端运行 android 而服务器运行 Java。
客户代码
package com.example.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.AsyncTask;
import java.io.*;
import java.net.*;
public class MainActivity extends Activity {
static String line= "works";
private MyTask mt;
private EditText nameField;
private TextView nameView;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameField =(EditText) findViewById(R.id.FirstInputField);
nameView =(TextView) findViewById(R.id.DisplayText);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mt=new MyTask();
mt.execute();
}
});
}
private class MyTask extends AsyncTask<Void, String, Void>
{
protected void onPreExecute()
{
}
@Override
protected Void doInBackground(Void... params) {
Socket s;
try {
s = new Socket ("172.17.20.42", 8888);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ios=new ObjectInputStream(s.getInputStream());
oos.writeObject(line);
oos.close();
ios.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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.main, menu);
return true;
}
}
该程序运行良好,但问题是,我正在发送静态字符串。
doInBackground方法无权访问 UI 线程。问题是“如何发送在 UI 中输入的字符串?”
先感谢您