Android在活动中调用异步任务

时间:2012-08-18 01:41:27

标签: android class android-activity android-asynctask

我有一个从gridview中选择图像的活动,它允许您保存图像。我正在为我的所有代码使用异步任务。我从几个类中分离了我的AsyncTask。我如何通过我的活动给他们打电话?如何将字符串传递回AsyncTask。

SingleImageView.class

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.save_image:
                new SaveImageTask().execute(image_url,context); //<-- The method execute(String...) in the type AsyncTask<String,String,String> is not applicable for the arguments (String, Context)

                  return true;
            default:
                return false;
        }

SaveImageTask.class

 public class SaveImageTask extends AsyncTask<String, String, String>
    {
        private Context context;
        private ProgressDialog pDialog;
        String image_url;
        URL myFileUrl = null;
        Bitmap bmImg = null;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub

            super.onPreExecute();

            pDialog = new ProgressDialog(context);  //<<-- Couldnt Recognise
            pDialog.setMessage("Downloading Image ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub

            try {  
                myFileUrl = new URL(image_url);
                HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();   
                conn.setDoInput(true);   
                conn.connect();     
                InputStream is = conn.getInputStream();
                bmImg = BitmapFactory.decodeStream(is); 
            }
            catch (IOException e)
            {       
                e.printStackTrace();  
            }
            try {       

                String path = myFileUrl.getPath();
                String idStr = path.substring(path.lastIndexOf('/') + 1);
            File filepath = Environment.getExternalStorageDirectory();
            File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
                dir.mkdirs();
                String fileName = idStr;
                File file = new File(dir, fileName);
                FileOutputStream fos = new FileOutputStream(file);
                bmImg.compress(CompressFormat.JPEG, 75, fos);   
                fos.flush();    
                fos.close();       
            }
            catch (Exception e)
                    {
                        e.printStackTrace();  
                    }
            return null;   
        }
        @Override
        protected void onPostExecute(String args) {
            // TODO Auto-generated method stub

            pDialog.dismiss();

        }
    }

2 个答案:

答案 0 :(得分:15)

您创建SaveImageTask的新实例,然后调用其execute方法,将String参数传递给它(execute采用varargs)。

new SaveImageTask().execute("foo", "bar");

修改

由于AsyncTask使用Context,您需要通过构造函数传递它。

public class SaveImageTask extends AsyncTask<String, String, String>
{
    private Context context;
    private ProgressDialog pDialog;
    String image_url;
    URL myFileUrl = null;
    Bitmap bmImg = null;

    public SaveImageTask(Context context) {
        this.context = context;
    }

    ...

}

然后从AsyncTask调用Activity,如下所示:

new SaveImageTask(this).execute("foo", "bar");

答案 1 :(得分:0)

private PopupWindow popupWindow;
// this function will be on MainActivity class


 findViewById(R.id.main_page_layout).post(new Runnable() {
               public void run() {

                   new SendJsonValue ().execute();
                   }
                });

public class SendJsonValue extends AsyncTask<String, Void, String>{

        @Override

        protected void onPreExecute(){
            /*code for pop window initialization begins here*/      
                LayoutInflater layoutInflater =(LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                  final View popupView = layoutInflater.inflate(R.layout.popup_window, null);
                  popupWindow = new PopupWindow(
                         popupView, 
                         LayoutParams.FILL_PARENT,  
                               LayoutParams.FILL_PARENT);  //creating popup
                  popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
        }

        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            //loadingMore = true;//parameter to take control on load more
            HttpClient httpclient = new DefaultHttpClient();
            final HttpParams httpParams = httpclient.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 30000);//set time out for receiving response
            HttpConnectionParams.setSoTimeout(httpParams, 30000);
            HttpPost httppost = new HttpPost("http://10.0.2.2/upload_test/InsertData.php");  

            try{

                BasicNameValuePair idValuePair = new BasicNameValuePair("dev_id", device_id);
                BasicNameValuePair emailValuePair = new BasicNameValuePair("dev_email", device_email);
                BasicNameValuePair jsonStringValuePair = new BasicNameValuePair("json", jObjectMain.toString());

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(idValuePair);
                nameValuePairs.add(emailValuePair);
                nameValuePairs.add(jsonStringValuePair);

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


                HttpResponse response = httpclient.execute(httppost);  //response class to handle responses
                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

                JSONObject object = new JSONObject(jsonResult);



        }catch(ConnectTimeoutException e){

        }catch (ClientProtocolException e) {  
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace(); 
        }catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch(Exception e){

        }

            return jsonResult;

    }
    protected void onPostExecute(String Result){


         System.out.println(Result);



        }
        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
             while ((rLine = rd.readLine()) != null) {
              answer.append(rLine);
               }
            }

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