[챕터 2-8-2] 동기화
2020. 2. 19. 00:09ㆍAndroid/Android 챕터 2-8
반응형
결과화면
실행버튼 클릭 시 프로그레스바가 점차적으로 변화 (좌측에서 우측으로)
프로젝트명 : MyAsyncTask
프로그레스바 : 레이아웃 마진 하단 30dp
MainActivity.java
더보기
package org.minokuma.myasynctask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = findViewById(R.id.progressBar);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
class BackgroundTask extends AsyncTask<Integer, Integer, Integer> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected Integer doInBackground(Integer... integers) {
return null;
}
}
}
MainActivity.java
더보기
package org.minokuma.myasynctask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
int value = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressBar);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.execute();
}
});
}
class BackgroundTask extends AsyncTask<Integer, Integer, Integer> {
@Override
protected void onPreExecute() {
value = 0;
progressBar.setProgress(value);
}
@Override
protected void onPostExecute(Integer integer) {
progressBar.setProgress(0);
}
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0].intValue());
}
@Override
protected Integer doInBackground(Integer... integers) {
while (!isCancelled()){
value += 1;
if(value >= 100){
break;
}
publishProgress(value);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return value;
}
}
}
반응형
'Android > Android 챕터 2-8' 카테고리의 다른 글
[챕터 2-8-1] 스레드 (0) | 2020.02.18 |
---|