android - 正确使用 AsyncTask get()

标签 android android-asynctask

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

异步任务

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 秒的黑屏。

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

关于android - 正确使用 AsyncTask get(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16007137/

相关文章:

java - ImageView无法一张一张显示图片

java - Postgresql 与 Java 中的数据库连接失败

android - Google Drive GET_CONTENT Intent 读取文件

android - 如何将 onClickListener 附加到不可见 View

android - 如何在 AsyncTask 运行时禁用 Button? (安卓)

android - 在单独的线程中填充 ListView

Android,线程 - 处理程序/异步任务

Android - 无法在未调用 Looper.prepare() 的线程内创建处理程序

android - 下载多个文件 : DownloadManager or AsyncTasks

java - 没有方法在 RemoteViewsService 中触发 - Android