正确使用AsyncTask的获得()正确、AsyncTask

2023-09-04 04:07:30 作者:殇丶残云

我遇到了一个问题。我需要使用的AsyncTask来检索JSON数据,我需要那个数据我提出的方案的下一部分之前。但是,使用的AsyncTask的get()方法时,我有5至8秒黑屏之前,我看到的是显示的数据。我想显示的数据检索过程中的进度对话框,但我不能因黑屏做到这一点。有没有一种方法添加到另一个线程?这里是一些code

的AsyncTask

 公共类DataResponse扩展的AsyncTask<字符串,整数,数据和GT; {

    AdverData代表;
    数据DATAS =新的Data();
    阅读器阅读器;
    语境myContext;
    ProgressDialog对话框;
    字符串temp1中;

公共DataResponse(上下文appcontext){

    myContext = appcontext;
    }

@覆盖
在preExecute保护无效()
{
    对话框=新ProgressDialog(myContext);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(假);
    dialog.setMessage(检索...);
    dialog.show();
};

    @覆盖
    保护数据doInBackground(字符串... PARAMS){
        的temp1 = PARAMS [0];
        尝试
        {
            InputStream的源= retrieveStream(temp1中);
            读者=新的InputStreamReader(源);
        }
        赶上(例外五)
        {
            e.printStackTrace();
        }

            GSON GSON =新GSON();
            DATAS = gson.fromJson(读卡器,Data.class);


            返回DATAS;


    }


    @覆盖
    保护无效onPostExecute(数据资料)
    {

             如果(dialog.isShowing())
            {
                dialog.dismiss();
            }

    }



    私人的InputStream retrieveStream(字符串URL){

            DefaultHttpClient客户端=新DefaultHttpClient();

            HTTPGET调用getRequest =新HTTPGET(URL);

            尝试 {

               HTT presponse GETRESPONSE = client.execute(调用getRequest);
               。最终诠释状态code = getResponse.getStatusLine()的getStatus code();

               如果(状态code!= HttpStatus.SC_OK){
                  Log.w(的getClass()。getSimpleName(),
                      错误+状态code +的URL+网址);
                  返回null;
               }

               HttpEntity getResponseEntity = getResponse.getEntity();
               返回getResponseEntity.getContent();

            }
            赶上(IOException异常E){
               getRequest.abort();
               Log.w(的getClass()getSimpleName(),错误的URL+网址,E);
            }

            返回null;

         }
 

}

DisplayInfo

 公共类DisplayInfo扩展活动实现AdverData {

公共静态数据的数据;
公共ProjectedData attup;
公共ProjectedData attdown;
公共ProjectedData sprintup;
公共ProjectedData sprintdown;
公共ProjectedData verizionup;
公共ProjectedData veriziondown;
公共ProjectedData tmobileup;
公共ProjectedData tmobiledown;
公共ProjectedAll转移;
私人ProgressDialog对话框;
公共DataResponse DATAR;

意图myIntent; //得到previously创建意图
双X; //将返回X
双Y; //将返回Y
INT空间; //将返回空间


//公共静态语境appContext;

@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);

    StrictMode.ThreadPolicy政策=新StrictMode。
            ThreadPolicy.Builder()permitAll()建立()。;
            StrictMode.setThreadPolicy(政策);

    对话框=新ProgressDialog(DisplayInfo.this);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(假);
    dialog.setMessage(检索...);
    dialog.show();

        myIntent = getIntent(); //得到previously创建意图
         X = myIntent.getDoubleExtra(×,0); //将返回X
         Y = myIntent.getDoubleExtra(Y,0); //将返回Y
         空间= myIntent.getIntExtra(空间,0); //将返回空间

        字符串的URL =某些URL






DATAR =新DataResponse()执行(attUp)获得()。






@覆盖
公共无效的OnStart()
{更多code}
 

解决方案 Android之AsyncTask机制篇

当您使用 GET ,使用异步任务没有任何意义。因为的get()将阻塞UI线程,这就是为什么正面临着如你上面提到的黑屏3到5秒。

不要使用的get()而使用的AsyncTask与回拨检查此AsyncTask与回调接口

I am running into a problem. I need to use asynctask to retrieve JSON data and i need that data before i moved on 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 an 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

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}

解决方案

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.

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