正确使用AsyncTask get()

问题描述 投票:2回答:2

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

的AsyncTask

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;

         }

}

DisplayInfo

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}
android android-asynctask
2个回答
11
投票

当您使用get时,使用Async Task没有任何意义。因为get()将阻止UI线程,这就是为什么面对3到5秒的空白屏幕,如上所述。

不要使用get()而是使用带回调的AsyncTask检查此AsyncTask with callback interface


0
投票

AsyncTask.get() - > Future.get()

如果需要等待计算完成,然后检索其结果。

Java Future表示异步任务的结果。

调用方法get()会阻塞当前线程并等待调用完成后再返回实际结果

您可以在单独的线程中调用get(),并根据您的体系结构构建逻辑。

调用get()可能需要相当长的时间。您可以采用两种方法,而不是浪费时间:

  • 使用AsyncTask.get(long timeout, TimeUnit unit) - > Future.get(long timeout, TimeUnit unit),但设置超时值作为参数,以防止你出现问题时卡住。
  • 使用isDone()方法,快速查看Future并检查它是否已完成其工作。

阅读更多here

© www.soinside.com 2019 - 2024. All rights reserved.