1

I have an application which logs in into a webservice. I start a new thread when the login button is clicked and show a progress dialog while the device is communicating with the server. Based on the success or failure of the attempt I send a message to the handler of 1 - success and -1 -failure. But how do I create and start a new intent based on this message? Or how should I handle this situation otherwise. Here is my code for the Login Activity:

public class Login extends Activity implements OnClickListener {

private static final int DIALOG = 0;
private static String TAG="LoginActivity";
private ProgressDialog progressDialog;

private final Handler handler =  new Handler() {
    public void handleMessage(Message msg) {

        int state = msg.arg1;
        if (state != 0)
        {
            Log.i(TAG, "dialog dismissed, message received "+state);
            dismissDialog(DIALOG);
        }


    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    View loginButton = findViewById(R.id.login_button);
    loginButton.setOnClickListener(this);

}

public void onClick(View v) {

    switch (v.getId()) {
    case R.id.login_button:
        Log.i(TAG,"login button");
        showDialog(DIALOG);

        Intent i = new Intent(this, PTVActivity.class);
        startActivity(i);
        break;

    }
}

protected Dialog onCreateDialog(int id)
{
    switch(id) {
    case DIALOG:
        progressDialog = new ProgressDialog(Login.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.login_progress));
        return progressDialog;
    default:
        return null;
    }
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    switch(id) {
    case DIALOG:

        EditText nameText=(EditText)findViewById(R.id.login_name);
        EditText pwText=(EditText)findViewById(R.id.password);
        String name = nameText.getText().toString();
        String pw = pwText.getText().toString();

        CommunicateServer communicate= new CommunicateServer(name,pw,handler);
        communicate.run();
    }


}

}

and here is the run() method of my CommunicateServer class:

@Override
public void run() {


    Message msg = handler.obtainMessage();
    if (login()==true)msg.arg1 = 1;
    else msg.arg1 = -1;
    handler.sendMessage(msg);

}
4

1 に答える 1

0

新しいインテントを作成してアクティビティを開始するには、次のことを行う必要があります。

Intent intent = new Intent(Login.this, anotherActivity.class);
startActivity(intent);

このタイプの作業を処理する最も簡単な方法は、 AsyncTask (例)を使用することです。

あなたの場合、 AsyncTask のonPreExecute()メソッドで進行状況ダイアログを表示する必要があります。

doInBackground(..) では、認証のためにサーバー呼び出しを行います。doInBackground(..) メソッドからステータス (1 または -1) を返す必要があります。

最後に、 onPostExecute(..)メソッドでパラメーターとしてステータス値 (1 または -1) を取得します。ここでは、ステータスに基づいて決定を下します。1 の場合、Activity を開くための新しいインテントを作成します。このメソッドでは、進行状況ダイアログも閉じる必要があります。

于 2012-06-13T20:57:48.237 に答える