android - 在android中的客户端服务器连接中使用异步任务

标签 android android-asynctask server-communication

我对 android 中的异步任务有疑问。我在下面的 Activity 中有两个服务器调用。我需要知道我应该将以下代码放在我的 Activity 中的什么位置:

new serverConnection().execute();

还有我的 Activity 代码要放在里面

@Override
protected Void doInBackground(Void... params) {
}

还有我要放在里面的 Activity 的剩余代码

@Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }

我不知道在要完成两个服务器调用的情况下使用异步任务的正确方法。如果只有一个服务器调用,那对我来说不是问题。但是当两个服务器调用同时到来时,我不知道正确的做法。而且我已经尝试了很多次,但仍然无法正确执行。有人可以帮我解决这个问题吗?

EDIT:::在这种情况下我必须使用两个异步任务吗??

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;
}

最佳答案

  1. 无论您做什么与网络相关的事情,都应该在 AsyncTask 的“doInBackground()”函数中完成

  2. 如果您有两次对服务器的调用并且都是独立的,那么您可以同时启动 2 个 AsyncTasks。

  3. 如果它们相互依赖,您可以将这两个调用集中在一个 AsyncTask 中。 IE。第二次服务器调用在第一次完成后开始。

编辑:

  1. 使用 2 个 AsyncTasks。调用第一个任务,进行身份验证。
  2. 在第一个 AsyncTask 的 onPostExecute 中,检查用户是否已从任务结果注册。
  3. 根据结果,如果要启动下一个服务器连接,请从第一个的onPostExecute 启动第二个AsyncTask。如果出现错误/失败,则从第一个任务的 onPostExecute 抛出一些用户反馈

关于android - 在android中的客户端服务器连接中使用异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22466834/

相关文章:

java - 从命令行编译时出现 com.android.dex.DexIndexOverflowException

android - 与服务器同步

java - 如何判断读取结束

Android异步任务与否

c# - Server A(C#)与B(C)通信解决方案

java - 关闭 Android 应用程序后丢失数据

java - 如何将背景图片添加到我的菜单中?

android - 如何避免在 onDraw 方法中创建对象

C# - 为高端服务器使用异步

java - AsyncTask 传递一个数组给 onProgressUpdate()