我的主要Android应用程序的类文件中有两个类。它的主要活动和AsyncTask。我在调用AsyncTask时传递用户名和密码字符串,但我想从主活动传递一个布尔值和字符串。我将在下面的代码中解释它(请检查代码中的注释):
//I have an main class
public class MyActivity extends Activity {
boolean clicked = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//stuff
login = (Button) findViewById(R.id.button1);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
//DO something
clicked = true;
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(getUsername(), getPassword()); //Here I want to pass boolean clicked, which will be checked on asynctask!
break;
}
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
if clicked == true{
//do something
}else{
//do something
}
}
}
对于经常使用Java的人来说,这可能不是那么复杂的问题,我不会这样,这就是我要问的原因......
提前致谢!
答案 0 :(得分:1)
AsyncTaskRunner是MyActivity类的非静态内部类,因此您已经可以在任何AsyncTaskRunner实例方法中访问Activity的“clicked”字段。您无需执行任何操作即可在AsyncTaskRunner方法中查看“已点击”字段。
如果声明AsyncTaskRunner是Static类。这是代码:
private static class AsyncTaskRunner extends AsyncTask<String, String, String> {
private final boolean clicked;
//private final Object anotherParams;
public AsyncTaskRunner(boolean clicked ) {
this.clicked = clicked;
}
public boolean isClicked() {
return clicked;
}
@Override
protected String doInBackground(String... strings) {
}
}
使用AsyncTaskRunner
AsyncTaskRunner runner = new AsyncTaskRunner(MyActivity.this.clicked);
答案 1 :(得分:0)
为您的AsyncTaskRunner
类创建一个构造函数,并将您的参数传递给构造函数,然后在AsyncTaskRunner
类方法中使用它们。
答案 2 :(得分:0)
您可以将其作为数组中的一个字符串传递:
runner.execute(String.valueOf(clicked), getUsername(), getPassword());
AsyncTask将获取它:
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... strings) {
boolean clicked = Boolean.parseBoolean(strings[0]);
String user = strings[1];
String pass = strings[2];
...
}
}