The way that I have my current application set up is that when you press the button then the app displays a counter on the bottom that goes up to ten then stops and then it displays a counter on the top that goes from 10 to 0. However, what I need to do is make these counters happen at the same time. I tried using threads but I think that I must not have been doing it right. Any help would be appreciated.
edit: I want to run mytask and mytask1 at the same time, they currently run after each other
edit2: I was asked for the code for publish progress
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
Code:
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]);
}
}
}
AsyncTasks根据文档在单个线程上执行,因此可能是问题所在。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.