我对android中的异步任务有疑问。我在下面的活动中有两个服务器调用。我需要知道将下面的代码放在我的活动中:
new serverConnection().execute();
我的活动代码也将放在
中@Override
protected Void doInBackground(Void... params) {
}
我的活动的剩余代码将放在
中@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
我不知道在两个服务器调用完成时使用异步任务的正确方法。如果只有一个服务器调用,那对我来说不会有问题。但是当两个服务器呼叫同时出现时,我并不知道正确的方法。我已经尝试了很多次,但仍然无法正确完成。有人可以帮我解决这个问题吗?
编辑:::在这种情况下我是否必须使用两个异步任务?
package com.example.onlineauction;
import java.util.Calendar;
import com.example.onlineauction.MainPage.serverConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressDialog dialog=null;
String keyfail;
Calendar cal=Calendar.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText username1=(EditText)findViewById(R.id.username);
final EditText password1=(EditText)findViewById(R.id.password);
Button login=(Button)findViewById(R.id.login);
Button register=(Button)findViewById(R.id.register);
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new serverConnection().execute();
CallSoap cs=new CallSoap();
try{
String username=username1.getText().toString();
String password=password1.getText().toString();
keyfail="Failed login";
//Calling the server first time and getting response from server
String response=cs.calllogin(username,password);
if(response.equalsIgnoreCase("Failed login"))
{
AlertDialog.Builder ab=new AlertDialog.Builder(MainActivity.this);
ab.setTitle("Clear the errors");
ab.setMessage("Either Username or Password is Incorrect");
ab.setCancelable(false);
ab.setPositiveButton("OK I will clear it",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alertdialog=ab.create();
alertdialog.show();
}
else
{
//THis is the second call to the server and getting name from server
String name=cs.retreivename(username, password);
//String[] columns = name.split(" ");
//Log.d("Count: ",count);
//assert columns.length == 2;
//String message1=columns[0];
//String message2=columns[1];
String keysuccess,keyfail = null,keyname;
keysuccess="Success";//
//keyname=message2;
Log.d("Message: ",response);
Log.d("Name of user: ",name);
if(response.equals(keysuccess))
{
Toast.makeText(MainActivity.this,"Login Success",Toast.LENGTH_LONG).show();
Intent i1=new Intent(MainActivity.this,Category.class);
SharedPreferences sp1=getSharedPreferences("My_login", MODE_PRIVATE);
Editor editor=sp1.edit();
editor.putString("name", name);
editor.putString("username",username);
editor.putString("password",password);
editor.commit();
startActivity(i1);
}
}
}
catch(Exception ex)
{
Log.d("Exception in main activity", "Activity main");
}
}
});
register.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in=new Intent(MainActivity.this, NewRegistration.class);
startActivity(in);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.i1:
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//finishFromChild(Activity Registration.class);
System.exit(0);
finish();
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
//This is the code for async task.
public class serverConnection extends AsyncTask<Void, String, Void> {
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
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.set, menu);
return true;
}
}
答案 0 :(得分:1)
您应该将所有连接/网络代码放在doInBackground()中,然后如果需要更新ui,则应该在onPostExecute()中执行此操作
答案 1 :(得分:1)
无论你做什么网络相关的事情,都应该在&#39; doInBackground()&#39;内完成。 AsyncTask的功能
如果您有两次对服务器的调用且两者都是独立的,那么您可以一次启动2个AsyncTasks。
如果它们是依赖的,你可以在一个AsyncTask内部进行两个调用。即。第1次服务器调用在第1次完成后开始。
编辑: