首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在测试异步任务完成之前,ImageDownload异步任务即将启动。

在测试异步任务完成之前,ImageDownload异步任务即将启动。
EN

Stack Overflow用户
提问于 2014-03-20 11:45:47
回答 4查看 264关注 0票数 0
代码语言:javascript
复制
public class DetailsActivity extends Activity {

private ArrayAdapter<Imageclass> adapter;
ArrayList<String> imageselect = new ArrayList<String>();
private ArrayList<Imageclass> array1;
private ArrayList<Imageclass> list = new ArrayList<Imageclass>();
//private ArrayList<Imageclass> array;
ArrayList<String> imagetest = new ArrayList<String>();
private TextView textView1; 
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
int id;
int pid;
int val;
int val_new;
double lati;
double longi;
String imagename;
//private ImageView image;
//public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
ImageView image;
static Bitmap bm;
ProgressDialog pd;


BitmapFactory.Options bmOptions;

public class test extends AsyncTask<Void, Void, InputStream>{

    ArrayList<Imageclass> str;

    private DetailsActivity activity;


    public test(DetailsActivity activity){
        this.activity = activity;
    }


    @Override
    protected InputStream doInBackground(Void... params) {

        //String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id); 
        Log.e("Checking id",""+id);

        String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id);
        URL url; 
        try {
            stringURL=stringURL.replaceAll(" ", "%20");

            url = new URL(stringURL);
            Log.e("URL",""+ url); 

            URLConnection conn= url.openConnection();

            Log.e("URLConnection",""+conn );
            InputStream stream= conn.getInputStream(); 

            Log.e("URLStream",""+stream );

            return stream; 
        } catch (MalformedURLException e) { 

            e.printStackTrace();
        } catch (IOException e) {

            Log.e("Excepiton", ""+e);
            e.printStackTrace();
        }
        return null;
    }       

    @Override
    protected void onPostExecute(InputStream result) {
        super.onPostExecute(result);
        Log.e("Result", ""+result);
        StringBuilder builder = new StringBuilder();
        Log.e("Builder", ""+ builder);
        BufferedReader reader = new BufferedReader(new InputStreamReader(result));
        Log.e("Reader", ""+ reader);

        String line = null;
        try {
            while((line = reader.readLine()) != null) {
                Log.e("Result11", ""+ builder.append(line));
                builder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        String jsonString = builder.toString();
        Log.e("image", jsonString);

        try {

            JSONObject rootObject = new JSONObject(jsonString);
            Log.e("JSOnObject",""+ rootObject);
            JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images");        
            //array1.clear();
            ArrayList<String> imagearray = new ArrayList<String>();
            for (int index = 0; index < jsonArray.length(); index++) {
                Imageclass imageinstance = new Imageclass(); 

                JSONObject object = (JSONObject) jsonArray.get(index);
                Log.e("Image test", "" + object);
                imageinstance.image = object.getString("file_name");

                //### this contain the image name
                Log.e("Imageinstance.image",""+imageinstance.image);

                imagename = imageinstance.image;
                imagearray.add(imageinstance.image);


                array1.add(imageinstance);
                //array1.add(imagearray);
                Log.e("array1","test"+array1);
            }
            Log.e("IMAGES",""+array1);
            activity.setlist(array1);


        }       
        catch (JSONException e) {
            Log.e("this Exception",""+ e);
            e.printStackTrace();
        }
        catch (Exception e) {
            Log.e("NULL","NULL"+e);
        }

        //  adapter.notifyDataSetChanged();


    }

}

代码语言:javascript
复制
public class ImageDownload extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... param) {
        bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
        Log.e("inside img",""+Finalname);
        Log.e("inside img_val",""+val);
        Log.e("Check","check"+imageUrl);
        loadBitmap(imageUrl, bmOptions);
        return imageUrl;
    }

    protected void onPostExecute(String imageUrl) {
        pd.dismiss();
        if (!imageUrl.equals("")) {
            Log.e("Test","Test"+ imageUrl.equals(""));
            image.setImageBitmap(bm);
        } else {
            Toast.makeText(DetailsActivity.this,
                    "test", Toast.LENGTH_LONG)
                    .show();
        }
    }

}

public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        bm = BitmapFactory.decodeStream(in, null, options);
        in.close();
    } catch (IOException e1) {
    }
    return bm;
}

private static InputStream OpenHttpConnection(String strURL)
        throws IOException {
    InputStream inputStream = null;
    URL url = new URL(strURL);
    URLConnection conn = url.openConnection();

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpConn.getInputStream();
        }
    } catch (Exception ex) {
    }
    return inputStream;
}

String Finalname;

//String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname;
public void setlist(ArrayList<Imageclass> list)
{
    this.list= list; 
    Log.e("LIST",""+ this.list);
    String imagename1 = list.toString();
    Log.e("image new value",""+imagename1);
    this.list= list; 
    Log.e("testing",""+ this.list); 
    for (int i=0; i < list.size(); i++)
    { 
        Log.e("new check",""+list.get(i));
        //String test2= list.get(i).toString();
        imagetest.add(list.get(i).toString());  
        Finalname = list.get(i).toString();
        getimage_name(Finalname);
        Log.e("Come",""+list.get(i).toString());
        Log.e("Finalname",""+Finalname);
    }
}
//String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;

private void getimage_name(String finalname2) {


}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_details);
    image = (ImageView)findViewById(R.id.imageView2);


    //  getMenuInflater().inflate(R.menu.details);
    //R.id.textDetailPlace 
    textView1 = (TextView)findViewById(R.id.textDetailPlace);
    textView2 = (TextView)findViewById(R.id.textDetailAddress ); 
    textView3 = (TextView)findViewById(R.id.textCapacity);
    //  textView4 = (TextView)findViewById(R.id.textDetailContactNo);
    textView5 = (TextView) findViewById(R.id.textViewDescription);


    textView1.setText(getIntent().getExtras().getString("test"));
    textView2.setText(getIntent().getExtras().getString("test2"));
    textView3.setText(getIntent().getExtras().getString("test3"));
    //textView4.setText(getIntent().getExtras().getString("test4"));
    textView5.setText(getIntent().getExtras().getString("test5"));

    id = getIntent().getExtras().getInt("test6");
    Log.e("ID value",""+id);

    pid = getIntent().getExtras().getInt("test7");
    Log.e("PID value",""+pid);

    lati = getIntent().getExtras().getDouble("testlat");
    Log.e("long",""+lati);
    longi = getIntent().getExtras().getDouble("testlong");
    Log.e("long",""+longi);
    val=pid;
    Log.e("val",""+val);
    ActionBar actionBar = getActionBar();
    actionBar.hide();
    pd = ProgressDialog.show(DetailsActivity.this, null, null,true);
    pd.setContentView(R.layout.progress);
    array1 = new ArrayList<Imageclass>();
    //new test(this).execute();

    new test(this).execute();

这里,测试异步任务被调用

代码语言:javascript
复制
    Log.e("JUST","CHECK");
    Log.e("JUST","CHECK");


    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

这里调用的是imageDownload异步任务:

代码语言:javascript
复制
    new ImageDownload().execute();

        Log.e("imagename",""+imagename);
}
}

在测试异步任务完成之前,在ImageDownload开始执行之前

我无法得到任务的状态,你能知道它是如何完成的吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-03-24 09:05:34

随着时间的推移,安卓处理AsyncTasks的方式也发生了一些变化。在非常老的安卓版本(前1.6AFAIK)中,多个AsyncTasks按顺序执行。这种行为已经改变为并行运行AsyncTasks,直到Android2.3。从Android3.0开始,Android团队决定人们在同步并行运行的任务时不够小心,并将默认行为切换回顺序执行。在内部,AsyncTask使用可以配置为按顺序(默认)或按需要并行运行的ExecutionService:

代码语言:javascript
复制
ImageLoader imageLoader = new ImageLoader( imageView );
imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png"    );
票数 0
EN

Stack Overflow用户

发布于 2014-03-20 12:03:01

无论我从这里了解到什么,您都希望在任务线程之后执行ImageDownload线程,因此从任务线程的onPostExecute()启动ImageDownload线程

票数 1
EN

Stack Overflow用户

发布于 2014-03-20 12:04:56

在执行异步任务时,将启动一个新线程,但当前线程将继续运行。它在启动thread.sleep后立即运行到test.async (1000)中。

它看起来像是在test.async中下载一些互联网,正如您可能已经猜到的,它需要超过1000毫秒(1秒)。这意味着1秒后,您的另一个异步将在第一个完成之前启动。

我猜你是想把他们弄乱。在第一个异步的postExecute中,您可以生成第二个异步。更正确的方法是在您的活动上实现一个接口,该接口在异步完成时进行回调,然后在收到回调后启动第二个异步。

下面是一个如何构造这个结构的例子。

代码语言:javascript
复制
interface AsyncCallback{
void onAsyncComplete();
}

public class ExampleActivity extends Activity implements AsyncCallback {

....

public void launchFirstAsync(){
    new Task(this).execute();
}


@Override
public void onAsyncComplete() {
    //todo launch second asyncTask;

   }
}

class Task extends AsyncTask<Void, Void, Void>{

AsyncCallback cb;

Task(AsyncCallback cb){
    this.cb = cb;
}

@Override
protected Void doInBackground(Void... params) {
    // TODO Auto-generated method stub
    return null;
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();

    cb.onAsyncComplete();
}

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22531961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档