AsyncTask의 progressDialog
http 서버에서 rss 피드를로드하는 동안 사용자 지정 진행률 대화 상자를 표시하려고하는데 하드 검색을했지만이 작업을 수행하는 데 도움이되지는 않았습니다. 내가 아는 유일한 것은 솔루션이 AsyncTask를 사용해야한다는 것입니다. 이 AsyncTask에 전달할 매개 변수입니다. 내 활동은 다음과 같습니다.
import java.util.ArrayList;
import java.util.List;
import com.cyberesa.info.BaseFeedParser;
import com.cyberesa.info.Message;
import com.cyberesa.info.MessageListAdapter;
import com.cyberesa.info.R;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;
private MyProgressDialog dialog;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.sorties);
tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");
loadFeed();
}
private void loadFeed(){
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(this,titles);
this.setListAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (Throwable t){
Log.e("ImageLoader",t.getMessage(),t);
}
}
}
이것에 AsyncTask를 추가하도록 도와 주시겠습니까?
고마워, 후셈
/**
* this class performs all the work, shows dialog before the work and dismiss it after
*/
public class ProgressTask extends AsyncTask<String, Void, Boolean> {
public ProgressTask(ListActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
/** progress dialog to show user that the backup is processing. */
private ProgressDialog dialog;
/** application context. */
private ListActivity activity;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
activity.setMessages(titles);
return true;
} catch (Exception e)
Log.e("tag", "error", e);
return false;
}
}
}
public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;
private MyProgressDialog dialog;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.sorties);
tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");
// just call here the task
AsyncTask task = new ProgressTask(this).execute();
}
public void setMessages(List<Message> msgs) {
messages = msgs;
}
}
보기 수정자를 onPostExecute로 이동하여 수정 된 코드는 다음과 같습니다.
public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;
//private MyProgressDialog dialog;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.sorties);
tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");
new ProgressTask(Soirees.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
@Vladimir, 귀하의 코드가 매우 도움이되었습니다.
AsyncTask는 매우 유용합니다!
class QueryBibleDetail extends AsyncTask<Integer, Integer, String>{
private Activity activity;
private ProgressDialog dialog;
private Context context;
public QueryBibleDetail(Activity activity){
this.activity = activity;
this.context = activity;
this.dialog = new ProgressDialog(activity);
this.dialog.setTitle("查询经文");
this.dialog.setMessage("正在查询:"+tome+chapterID+":"+sectionFromID+"-"+sectionToID);
if(!this.dialog.isShowing()){
this.dialog.show();
}
}
@Override
protected String doInBackground(Integer... params) {
Log.d(TAG,"经文doInBackground");
publishProgress(params[0]);
if(sectionFromID > sectionToID){
return "";
}
String queryBible = "action=query_bible&article="+chapterID+"&id="+tomeID+"&verse_start="+sectionFromID+"&verse_stop="+sectionToID+"";
try{
String bible = (Json.getRequest(HOST+queryBible)).trim();
bible = android.text.Html.fromHtml(bible).toString();
return bible;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String bible){
Log.d(TAG,"经文onPostExecute");
TextView bibleBox = (TextView) findViewById(R.id.bibleBox);
bibleBox.setText(bible);
this.dialog.dismiss();
}
}
며칠 전에이 문제에 대한 아주 좋은 해결책을 찾았습니다. 여기에서 그것에 대해 읽어보십시오 . 두 단어로 Mike는 ProgressDialog와 AsyncTask를 중재하는 AsyncTaskManager를 만들었습니다. 이 솔루션을 사용하는 것은 매우 쉽습니다. 프로젝트에 여러 인터페이스와 여러 클래스를 포함하고 활동에 간단한 코드를 작성하고 BaseTask에서 새 AsyncTask를 중첩하면됩니다. 유용한 팁이 있기 때문에 댓글을 읽으라고 조언합니다.
어떤 매개 변수를 사용해야하는지 모르십니까?
를 포함한 많은 개발자들은 매개 변수의 모호성 때문에 AsyncTask를 처음 작성하는 데 어려움을 겪고 있습니다. 가장 큰 이유는 AsyncTask에서 사용되는 매개 변수를 기억하려고하기 때문입니다. 열쇠는 Do n't memorize 입니다. 작업이 실제로 수행해야하는 작업을 시각화 할 수 있다면 올바른 서명으로 AsyncTask를 작성하는 것은 케이크 조각이 될 것입니다.
AsyncTask 란 무엇입니까?
AsyncTask는 백그라운드 스레드에서 실행되는 백그라운드 작업입니다. 입력을 받고 진행을 수행하고 출력을 제공합니다.
즉
AsyncTask<Input,Progress,Output>
입력, 진행 및 출력이 무엇인지 파악하면 잘 될 것입니다.
예를 들면
매개 변수 는 어떻게
doInbackground()
변경AsyncTask
됩니까?
어떻게
doInBackground()
하고onPostExecute()
,onProgressUpdate()
관련?
이것을 코드로 어떻게 작성할 수 있습니까?
DownloadTask extends AsyncTask<String,Integer,String>{
@Override
public void onPreExecute(){
}
@Override
public String doInbackGround(String... params)
{
// Download code
int downloadPerc = // calculate that
publish(downloadPerc);
return "Download Success";
}
@Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
}
@Override
public void onProgressUpdate(Integer... params)
{
// show in spinner, access UI elements
}
}
활동에서이 작업을 어떻게 실행 하시겠습니까?
new DownLoadTask().execute("Paradise.mp3");
It's been a few years since this question was asked (and since someone has posted a response). Since then, ProgressDialog was deprecated in API level O, according to Android's official documentation. As such, you might consider using an inline progress bar instead of a ProgressDialog as the documentation authors suggest.
This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.
참고URL : https://stackoverflow.com/questions/4538338/progressdialog-in-asynctask
'Program Tip' 카테고리의 다른 글
열의 모든 데이터를 대문자로 만드는 SQL 쿼리? (0) | 2020.11.19 |
---|---|
PostgreSQL 기본 키를 1로 재설정 (0) | 2020.11.19 |
xml.LoadData-루트 수준의 데이터가 잘못되었습니다. (0) | 2020.11.19 |
Xamarin.Forms-새 페이지를 만들 때 InitializeComponent가 존재하지 않습니다. (0) | 2020.11.19 |
목록에서 대소 문자 구분을 무시하는 방법 (0) | 2020.11.19 |