10

我有一个从网格视图中选择图像的活动,它允许您保存图像。我正在为我的所有代码使用异步任务。我将我的 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();

        }
    }
4

2 回答 2

17

您创建一个新实例,SaveImageTask然后调用它的execute方法,将字符串参数传递给它(execute接受一个可变参数)。

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

编辑

由于您AsyncTask使用 a 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");
于 2012-08-18T01:43:52.330 回答
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;
           }  
    }
于 2013-11-07T09:29:12.650 回答