我有这个android代码:
private class myTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
try {
client = new Socket("192.168.1.2", 4444);
oos = new ObjectOutputStream(client.getOutputStream());
ois = new ObjectInputStream(client.getInputStream());
oos.writeUTF("LOGIN");
oos.flush();
String emailText = email.getText().toString();
oos.writeUTF(emailText);
oos.flush();
String passwordText = password.getText().toString();
oos.writeUTF(passwordText);
oos.flush();
string = ois.readUTF();
}catch (ConnectException e){
return "Host not found";
}catch (IOException e) {
return "Exception Caught";
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if ("Host not found".equalsIgnoreCase(result)){
Toast.makeText(getApplicationContext(), "Host not found" ,Toast.LENGTH_LONG).show();
}else if("Exception Caught".equalsIgnoreCase(result)){
Toast.makeText(getApplicationContext(), "Connection error" ,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Connection established" ,Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(), string ,Toast.LENGTH_LONG).show();
if(string.equals("Login successfully Done!")){
startActivity(new Intent(Login.this, User.class));
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
register = (TextView)findViewById(R.id.register);
login = (Button)findViewById(R.id.login);
email = (EditText)findViewById(R.id.email);
password = (EditText)findViewById(R.id.password);
connection = (TextView)findViewById(R.id.connection);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
register.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
startActivity(new Intent(Login.this, Register.class));
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new myTask().execute();
}
});
}
但是,每次我单击登录按钮时,我的连接就会创建。我希望我的应用程序在启动时连接到服务器,然后当我按登录按钮时,它将请求发送到服务器。
谢谢
我认为最简单的方法是从AsyncTasks移到Threads。在onCreate函数中创建一个新线程,该线程创建并连接套接字,然后让其等待UI线程的通知(最简单的方法是等待信号量或消息队列)。然后让按钮的onClick通知套接字线程它需要登录。使用这种设计,您可以在启动时将其连接,但只有在您请求时才能登录。
您最大的担心是服务器是否由于不活动而使连接超时。但是我认为您可以控制服务器来防止这种情况。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句