我有一个登录到网络服务的应用程序。单击登录按钮时,我会启动一个新线程,并在设备与服务器通信时显示进度对话框。根据尝试的成功或失败,我向 1 - 成功和 -1 - 失败的处理程序发送消息。但是如何根据此消息创建和启动新意图?或者我应该如何处理这种情况。这是我的登录活动代码:
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();
}
}
}
这是我的 CommunicateServer 类的 run() 方法:
@Override
public void run() {
Message msg = handler.obtainMessage();
if (login()==true)msg.arg1 = 1;
else msg.arg1 = -1;
handler.sendMessage(msg);
}