2012-10-26 25 views
11

Tôi biết rằng lần đầu tiên bạn thực hiện điều này là ... tại sao bạn lại sử dụng AsyncTask trên thế giới. Vì vậy, đây là vấn đề của tôi tôi đang làm việc trên một số ứng dụng Android (API 7 cho android 2.1 hoặc cao hơn), và tôi đang thử nghiệm trên giả lập và mọi thứ đều tốt, vì vậy sau đó tôi thử nghiệm trên HTC Sensation và nó nói NetworkOnMainThreadExeption!Android: cách đợi AsyncTask kết thúc trong MainThread?

Tôi đã tải xuống một số hình ảnh và sau đó vẽ trên bản đồ.

Vì vậy, để giải quyết vấn đề này mỗi (kết nối internet) trong trường hợp này tải xuống hình ảnh tôi phải đặt trên AsyncTask để hoạt động.

Vì vậy, tôi cần một phương pháp làm thế nào để biết khi nào tất cả các hình ảnh được thực hiện vì vậy tôi có thể bắt đầu vẽ ..

Tôi đã cố gắng rất nhiều và kết quả không có tôi không có ý tưởng. Tôi đã có một giải pháp với handler nhưng nếu chạy trên net chậm hơn tôi nhận được nullpointer (vì những hình ảnh không được tải về).

Vì vậy, hãy giúp tôi.

EDIT:

đây là ý tưởng:

Bitmap bubbleIcon ; 
    onCreate(){ 
    ... 
// i am making call for Async 
new ImgDown().execute(url); 
//and then i calling functions and classes to draw with that picture bubbleIcon ! 
DrawOnMap(bubbleIcon); 
} 




//THIS IS ASYNC AND FOR EX. SUPPOSE I NEED TO DOWNLOAD THE PIC FIRST 
    class ImgDown extends AsyncTask<String, Void, Bitmap> { 

     private String url; 

     public ImgDown() { 
     } 

     @Override 
     protected Bitmap doInBackground(String... params) { 
      url = params[0]; 
      try { 
       return getBitmapFromURL(url); 
      } catch (Exception err) { 
      } 

      return null; 

     } 

     @Override 
     protected void onPostExecute(Bitmap result) { 
      bubbleIcon = result; 
      bubbleIcon = Bitmap 
        .createScaledBitmap(bubbleIcon, 70, 70, true); 

     } 

     public Bitmap getBitmapFromURL(String src) { 
      try { 
       Log.e("src", src); 
       URL url = new URL(src); 
       HttpURLConnection connection = (HttpURLConnection) url 
         .openConnection(); 
       connection.setDoInput(true); 
       connection.connect(); 
       InputStream input = connection.getInputStream(); 
       // /tuka decode na slika vo pomalecuk kvalitet! 
       BitmapFactory.Options options = new BitmapFactory.Options(); 
       options.inSampleSize = 3; 
       Bitmap myBitmap = BitmapFactory 
         .decodeStream(new FlushedInputStream(input)); 
       Log.e("Bitmap", "returned"); 
       return myBitmap; 
      } catch (IOException e) { 
       e.printStackTrace(); 
       Log.e("getBitmapFromURL", e.getMessage()); 
       return null; 
      } 
     } 

     class FlushedInputStream extends FilterInputStream { 
      public FlushedInputStream(InputStream inputStream) { 
       super(inputStream); 
      } 

      public long skip(long n) throws IOException { 
       long totalBytesSkipped = 0L; 
       while (totalBytesSkipped < n) { 
        long bytesSkipped = in.skip(n - totalBytesSkipped); 
        if (bytesSkipped == 0L) { 
         int byteValue = read(); 
         if (byteValue < 0) { 
          break; // we reached EOF 
         } else { 
          bytesSkipped = 1; // we read one byte 
         } 
        } 
        totalBytesSkipped += bytesSkipped; 
       } 
       return totalBytesSkipped; 
      } 
     } 
    } 

tôi hy vọng bây giờ là rõ ràng hơn.

+0

Hãy dán mã nguồn có liên quan. Nó không thể giúp đỡ nếu bạn chỉ cung cấp mô tả không chính thức. –

+0

tôi đã chỉnh sửa bài đăng. xin vui lòng xem – user1730007

+0

Sử dụng hộp thoại tiến trình – WillingLearner

Trả lời

32
class OpenWorkTask extends AsyncTask { 

    @Override 
    protected Boolean doInBackground(String... params) { 
     // do something 
     return true; 
    } 

    @Override 
    protected void onPostExecute(Boolean result) { 
     // The results of the above method 
     // Processing the results here 
     myHandler.sendEmptyMessage(0); 
    } 

} 

Handler myHandler = new Handler() { 

    @Override 
    public void handleMessage(Message msg) { 
     switch (msg.what) { 
     case 0: 
      // calling to this function from other pleaces 
      // The notice call method of doing things 
      break; 
     default: 
      break; 
     } 
    } 
}; 
+6

BẠN LÀ NGƯỜI! Cảm ơn rất nhiều đó là những gì tôi đang tìm kiếm. CÁM ƠN NHIỀU, ÔNG BẠN! bạn là tốt nhất – user1730007

+1

bạn được chào đón – RookieWen

+0

Mã thực sự tuyệt vời đó là ... cảm ơn rất nhiều bạn thân ... –

2
class openWorkTask extends AsyncTask<String, String, Boolean> { 

    @Override 
    protected Boolean doInBackground(String... params) { 
     //do something 
     return true; 
    } 

    @Override 
    protected void onPostExecute(Boolean result) { 
     // The results of the above method 
     // Processing the results here 
    } 
} 
+0

Tôi không thể xử lý các kết quả ở đó, tôi có một vài cuộc gọi khác nhau để chức năng này từ các pleaces khác vì vậy .. tôi cần một phương pháp để biết khi nào AsyncTask sẽ kết thúc. – user1730007

+0

Bạn có thể gửi HandlerMessage khi thời gian hoàn thành việc thu thập dữ liệu mạng – RookieWen

+0

làm cách nào tôi có thể thực hiện điều đó? bạn có thể cho tôi ví dụ không. – user1730007

0

Tôi sẽ sử dụng Hộp thoại tiến trình nếu tôi là bạn. Bằng cách này, người dùng có thể thấy rằng một cái gì đó đang xảy ra trong khi ASyncTask tải hình ảnh xuống. Trên PostExecute, hãy gọi một phương thức từ mã chính của bạn để kiểm tra xem các hình ảnh có rỗng không. Hãy nhớ rằng bạn không thể cập nhật giao diện người dùng trong phương pháp doInBackground do đó, làm bất cứ công việc UI trong cả hai onPreExecute hoặc onPostExecute

private class DownloadPictures extends AsyncTask<String, Void, String> 
{ 

    ProgressDialog progressDialog; 

    @Override 
    protected String doInBackground(String... params) 
    { 

     //Download your pictures 

     return null; 

    } 

    @Override 
    protected void onPostExecute(String result) 
    { 

     progressDialog.cancel(); 

     //Call your method that checks if the pictures were downloaded 

    } 

    @Override 
    protected void onPreExecute() { 

     progressDialog = new ProgressDialog(
       YourActivity.this); 
     progressDialog.setMessage("Downloading..."); 
     progressDialog.setCancelable(false); 
     progressDialog.show(); 

    } 

    @Override 
    protected void onProgressUpdate(Void... values) { 
     // Do nothing 
    } 

} 
5

Bạn có thể viết Đại biểu của riêng bạn để ủy thác thông tin về hoàn thành nhiệm vụ, sử dụng nguyên tắc OOP:

task_delegate.java

public interface TaskDelegate { 
    void TaskCompletionResult(String result); 
} 

main_activity.java

public class MainActivity extends Activity implements TaskDelegate { 

    //call this method when you need  
    private void startAsynctask() { 
     myAsyncTask = new MyAsyncTask(this); 
     myAsyncTask.execute(); 
    } 

//your code 

    @Override 
    public void TaskCompletionResult(String result) { 
     GetSomethingByResult(result); 
    } 
} 

my_asynctask.java

public class MyAsyncTask extends AsyncTask<Void, Integer, String> { 

    private TaskDelegate delegate; 

    protected MyAsyncTask(TaskDelegate delegate) { 
     this.delegate = delegate; 
    } 

    //your code 

    @Override 
    protected void onPostExecute(String result) { 

     delegate.TaskCompletionResult(result); 
    } 
} 
Các vấn đề liên quan