我设置当前应用程序的方式是,当您按下按钮时,该应用程序在底部显示一个计数器,该计数器增加到十,然后停止,然后在顶部显示一个计数器,计数器从10到0。但是,我需要做的是使这些计数器同时发生。我尝试使用线程,但我想我一定做得不对。任何帮助,将不胜感激。
编辑:我想同时运行mytask和mytask1,它们当前彼此运行
edit2:要求我提供发布进度的代码
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
代码:
public class MainActivity extends AppCompatActivity {
Button btn;
TextView txt;
Integer count =1;
Integer count1 =10;
TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//p
//p
btn = (Button) findViewById(R.id.button);
btn.setText("Start");
txt = (TextView) findViewById(R.id.textView);
txt1 = (TextView) findViewById(R.id.textView2);
View.OnClickListener listener = new View.OnClickListener(){
public void onClick(View view){
count =1;
//p
//p
switch (view.getId()){
case R.id.button:
new MyTask().execute(10);
new MyTask1().execute(0);
break;
}
}
};
btn.setOnClickListener(listener);
}
class MyTask extends AsyncTask<Integer, Integer, String> {
@Override
protected String doInBackground(Integer... params) {
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
@Override
protected void onPostExecute(String result) {
txt.setText(result);
btn.setText("Restart");
}
@Override
protected void onPreExecute() {
txt.setText("Task Starting...");
}
@Override
protected void onProgressUpdate(Integer... values) {
txt.setText("BackGround Task Running..."+ values[0]);
}
}
class MyTask1 extends AsyncTask<Integer, Integer, String> {
@Override
protected String doInBackground(Integer... params) {
for (; count1 >= params[0]; count1--) {
try {
Thread.sleep(1000);
publishProgress(count1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
@Override
protected void onPostExecute(String result) {
txt1.setText(result);
btn.setText("Restart");
}
@Override
protected void onPreExecute() {
txt1.setText("Task Starting...");
}
@Override
protected void onProgressUpdate(Integer... values) {
txt1.setText("Countdown "+ values[0]);
}
}
}