1

Androidの非同期タスクについて疑問があります。以下のアクティビティで 2 つのサーバー呼び出しがあります。以下のコードをアクティビティのどこに配置すればよいかを知る必要があります。

new serverConnection().execute();

内部に配置されるアクティビティのコードも

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

そして、内部に配置されるアクティビティの残りのコード

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

2 つのサーバー呼び出しが行われる非同期タスクの適切な使用方法がわかりませんでした。サーバー呼び出しが 1 つしかない場合、それは問題にはなりません。しかし、2 つのサーバー呼び出しが同時に来た場合、適切な方法がわかりませんでした。何度も試しましたが、まだ正しく実行できません。この問題に関して誰かが私を助けることができますか??

編集:::この場合、2 つの非同期タスクを使用する必要がありますか??

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

}

4

2 に答える 2

1
  1. ネットワーク関連の操作は、AsyncTask の「doInBackground()」関数内で行う必要があります。

  2. サーバーへの呼び出しが 2 つあり、両方が独立している場合、一度に 2 つの AsyncTask を開始できます。

  3. それらが依存している場合は、1 つの AsyncTask 内で 2 つの呼び出しをクラブすることができます。すなわち。2 番目のサーバー呼び出しは、1 番目の呼び出しが完了した後に開始されます。

編集:

  1. 2 つの AsyncTask を使用します。最初のタスクを呼び出し、認証を行います。
  2. 最初の AsyncTask の onPostExecute 内で、タスクの結果からユーザーが登録されているかどうかを確認します。
  3. その結果によって、次のサーバー接続を開始したい場合は、1番目のonPostExecuteから2番目のAsyncTaskを開始します。エラー/障害が発生した場合は、最初のタスクの onPostExecute からユーザー フィードバックをスローします。
于 2014-03-17T22:45:13.620 に答える