2012-06-28 4 views
0

AsyncTask와 같은 서비스를 사용하고 싶습니다. 뒷 배경에있는 은 스트림을 열고 보류 중으로 프로세스 바를 표시합니다. 그것이 끝나면 백그라운드에서 수행 한 stream 매개 변수가 있습니다. 당신이 나에게 이것을 줄 간단한 코드를 줄 수 있다면.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(); 

가 지금은 서비스에 그 일을 구현할 수있는 방법을. 많은 예제가 있지만 간단한 것은 아닙니다. 간단한 코드를 게시하면 많은 도움이됩니다.

답변

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); 
    } 
} 
+0

죄송하지만이 아닌 서비스 나 연결을 할 수있는 서비스를 필요 –

관련 문제