* MainActivity.java
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
int value;
@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 task = new BackgroundTask();
task.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() == false) {
value++;
if (value >= 100) {
break;
}
publishProgress(value);
try {
Thread.sleep(1000);
} catch (Exception e) {
//
}
}
return value;
}
}
}
* activity_main.xml
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
int value;
@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 task = new BackgroundTask();
task.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() == false) {
value++;
if (value >= 100) {
break;
}
publishProgress(value);
try {
Thread.sleep(1000);
} catch (Exception e) {
//
}
}
return value;
}
}
}
'android' 카테고리의 다른 글
HttpURLConnection 사용법 (0) | 2020.02.04 |
---|---|
Socket 통신(Thread 필수) (0) | 2020.02.04 |
Thread 사용법 (0) | 2020.02.04 |
키패드 닫기 (0) | 2020.02.03 |
SeekBar 사용법 (0) | 2020.02.03 |