0

我想使用类似于 AsyncTask 的服务。在后台,它打开流并保持仅显示进程栏。当它完成时,它将具有在后台执行的流参数。如果你能给我一个简单的代码来做这个。

我的异步任务如下所示:

  protected void onPreExecute() {
      Dialog.setMessage("Doing something...");
      Dialog.show();          
  }

我的服务应该这样做:

  try{

     URL url = new URL("http://www.google.com");

     // Read all the text returned by the server
     BufferedReader in = new BufferedReader
                                 (new InputStreamReader(url.openStream()));
     String str;
     while ((str = in.readLine()) != null) {
        // str is one line of text;
         readLine() 
         strips the newline  character(s)
     }
     //all is ok
     in.close();

现在我该如何实现这些服务。我知道我有很多示例,但它们并不简单,如果您可以发布执行此操作的简单代码,那将有很大帮助。

4

1 回答 1

0

是的,这里是示例代码:

public void draw(int tot) throws IOException, URISyntaxException{

    total--;
    sv = new ScrollView(this);
    ll = new LinearLayout(this);
    ll.setBackgroundResource(R.drawable.opsbuds);
    ll.setOrientation(LinearLayout.VERTICAL);
    sv.addView(ll);

//  TextView tv1=new TextView(this);
    //tv1.setText("Question: "+question);
//  tv1.setTextColor(Color.rgb(80, 00, 80));
//  ll.addView(tv1);
    img=new ImageView(this);
    //Bitmap drawable = getBitmapFromURL("http://bufferedsoftware.com/survey/db/php/authentication/upload/" + option1[tot]);

    new DownloadFileFromURL().execute(); 

    Button btn=new Button(this);
    btn.setLayoutParams (new LayoutParams 
            (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp1.setMargins(20, 10, 0, 0);
    btn.setText("Question");
    btn.setTextSize(20);
    btn.setWidth(100);
    btn.setHeight(40);
    btn.setLayoutParams(lp1);
    btn.setTextColor(Color.rgb(80, 00, 80));
    btn.setBackgroundResource(R.drawable.button);
    btn.setOnClickListener(this);
    img.setLayoutParams(lp1);
    ll.addView(img);
    ll.addView(btn);
    this.setContentView(sv);
    temp++;
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type:
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading Image. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

class DownloadFileFromURL extends AsyncTask<String, String, String> {

     Bitmap bitmap;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }
    @Override
    protected String doInBackground(String... f_url) {  

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("tag", "format2"));
        nameValuePairs.add(new BasicNameValuePair("surveyId", surveyId));
        nameValuePairs.add(new BasicNameValuePair("quesNo", Integer.toString(ques_no)));
        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(surveyURL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
        }
        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line="0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }


        try{
            jArray = new JSONArray(result);
            JSONObject json_data=null;
            json_data = jArray.getJSONObject(0);
            quest_id=json_data.getString("question_id");
            question=json_data.getString("question");
            options=json_data.getString("op");
            option1=json_data.getString("image_name");
            quesNo=json_data.getString("question_no");
            help=json_data.getString("Help");
            mandatory=json_data.getString("mandatory");
            others=json_data.getString("others");
            condition=json_data.getString("condition1");
            total++;    
        }
        catch(JSONException e1)
        {
            Toast.makeText(getBaseContext(), "No Data Found" ,Toast.LENGTH_LONG).show();
        } catch (ParseException e1) 
        {
            e1.printStackTrace();
        }  

         try {
               URL url = new URL("http://182.71.220.141/survey/db/php/authentication/upload/" + option1);
               HttpGet httpRequest = null;

               httpRequest = new HttpGet(url.toURI());

               HttpClient httpclient = new DefaultHttpClient();
               HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

               HttpEntity entity = response.getEntity();
               BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
               InputStream input = b_entity.getContent();

              bitmap = BitmapFactory.decodeStream(input);
            } catch (MalformedURLException e) {
                Log.e("log", "bad url");
            } catch (IOException e) {
                Log.e("log", "io error");
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        return null;
}

    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        img.setImageBitmap(bitmap);
        dismissDialog(progress_bar_type);
    }
}
于 2012-06-28T12:09:53.253 回答