正确使用 AsyncTask get() [英] Properly Using AsyncTask get()

查看:13
本文介绍了正确使用 AsyncTask get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题.我需要使用 asynctask 来检索 JSON 数据,并且在转到程序的下一部分之前我需要这些数据.但是,当使用 AsyncTask 的 get() 方法时,在我看到数据显示之前,我有 5 到 8 秒的黑屏.我想在数据检索期间显示进度对话框,但由于黑屏而无法执行此操作.有没有办法放入另一个线程?这是一些代码

I am running into a problem. I need to use asynctask to retrieve JSON data and I need that data before I moved to the next part of the program. However, when using the get() method of AsyncTask I have 5 to 8 sec black screen before I see the data is displayed. I would like to display a progress dialog during the data retrieval but I cannot do this due to the black screen. Is there a way to put into another thread? here is some code

异步任务

public class DataResponse extends AsyncTask<String, Integer, Data> {

    AdverData delegate;
    Data datas= new Data();
    Reader reader;
    Context myContext;
    ProgressDialog dialog;
    String temp1;

public DataResponse(Context appcontext) {

    myContext=appcontext;
    }

@Override
protected void onPreExecute()
{
    dialog= new ProgressDialog(myContext);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(false);
    dialog.setMessage("Retrieving...");
    dialog.show(); 
};      

    @Override
    protected Data doInBackground(String... params) {
        temp1=params[0];              
        try
        {
            InputStream source = retrieveStream(temp1);
            reader = new InputStreamReader(source);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

            Gson gson= new Gson();
            datas= gson.fromJson(reader, Data.class);    


            return datas; 


    }


    @Override
    protected void onPostExecute(Data data) 
    {

             if(dialog.isShowing())
            {
                dialog.dismiss();
            }

    }



    private InputStream retrieveStream(String url) {

            DefaultHttpClient client = new DefaultHttpClient(); 

            HttpGet getRequest = new HttpGet(url);

            try {

               HttpResponse getResponse = client.execute(getRequest);
               final int statusCode = getResponse.getStatusLine().getStatusCode();

               if (statusCode != HttpStatus.SC_OK) { 
                  Log.w(getClass().getSimpleName(), 
                      "Error " + statusCode + " for URL " + url); 
                  return null;
               }

               HttpEntity getResponseEntity = getResponse.getEntity();
               return getResponseEntity.getContent();

            } 
            catch (IOException e) {
               getRequest.abort();
               Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
            }

            return null;

         }

}

显示信息

public class DisplayInfo extends Activity implements AdverData {

public static Data data;
public ProjectedData attup;
public ProjectedData attdown;
public ProjectedData sprintup;
public ProjectedData sprintdown;
public ProjectedData verizionup;
public ProjectedData veriziondown;
public ProjectedData tmobileup;
public ProjectedData tmobiledown;
public ProjectedAll transfer;
private ProgressDialog dialog;
public DataResponse dataR;

Intent myIntent; // gets the previously created intent
double x; // will return "x"
double y; // will return "y"
int spatial; // will return "spatial"


//public static Context appContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    StrictMode.ThreadPolicy policy = new StrictMode.
            ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy); 

    dialog= new ProgressDialog(DisplayInfo.this);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(false);
    dialog.setMessage("Retrieving...");
    dialog.show(); 

        myIntent= getIntent(); // gets the previously created intent
         x = myIntent.getDoubleExtra("x",0); // will return "x"
         y = myIntent.getDoubleExtra("y", 0); // will return "y"
         spatial= myIntent.getIntExtra("spatial", 0); // will return "spatial"

        String URL = "Some URL"






dataR=new DataResponse().execute(attUp).get();






@Override
public void onStart()
{more code}

推荐答案

当您使用 get 时,使用 Async Task 没有任何意义.因为 get() 会阻塞 UI 线程,这就是上面提到的为什么要面对 3 到 5 秒的空白屏幕.

When you are using get, using Async Task doesn't make any sense. Because get() will block the UI Thread, Thats why are facing 3 to 5 secs of blank screen as you have mentioned above.

不要使用 get() 而是使用带有回调的 AsyncTask 检查这个 带有回调接口的异步任务

Don't use get() instead use AsyncTask with Call Back check this AsyncTask with callback interface

这篇关于正确使用 AsyncTask get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆