2014-07-16 2 views
1

New to new android.처리기를 사용하여 backround 스레드 내의 UI를 업데이트하지 못했습니다.

URL에서 파일을 다운로드하는 프로그램을 작성 중이지만 배경 화면 스레드에서 다운로드 중일 때 textview를 읽은 현재 바이트로 업데이트해야합니다.

그러나, Log.d("","")에이 textview(lbStatus)

즉시하지만 업데이트 될 때 나는 모두 Handler 및하여 runOnUiThread() 방법은 실행 가능한 방법을 실행하는 데 사용하여 시도했다.

도와 주실 수 있습니까?이 문제에 대한 도움을 많이 주시면 감사하겠습니다.

DownloadThread 클래스 :

public class DownloadThread implements Runnable{ 

    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     URL myurl = null; 
     int read = -1; 
     HttpURLConnection httpconn; 
     InputStream is = null; 
     FileOutputStream ou = null; 

     try 
     { 
      myurl = new URL(fileurl); 
     } 
     catch (MalformedURLException e1) 
     { 
      // TODO Auto-generated catch block 
      Log.d("mree",""+e1);  
     } 

     try { 

       URLConnection urlconn = myurl.openConnection(); 
       httpconn = (HttpURLConnection)urlconn; 
       is = httpconn.getInputStream(); 
       int len= httpconn.getContentLength();   
       File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+Uri.parse(fileurl).getLastPathSegment());    
       ou = new FileOutputStream(file); 
       read = is.read(); 
       CurrByte = 0; 

       myhandler.post(new MainActivity.UpdateS(len)); 
       //runOnUiThread(new MainActivity.UpdateS(len)) 

       while(read != -1) 
       { 
       CurrByte++; 
       ou.write(read); 
       read = is.read();     
       } 


     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      Log.d("mree","Error Message: "+e); 
     } 
     finally 
     { 
      if (is != null) 
      { 
       try { 
        is.close(); 

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

      if (ou != null) 
      { 
       try { 
        ou.close(); 
        } 
       catch (IOException e) 
       { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       } 
      } 
     } 


    } 

} 

업데이트 클래스 :

public class UpdateS implements Runnable{ 
     int filelength; 
     UpdateS(int len) 
     { 
      this.filelength = len; 
     } 
     @Override 
     public void run() { 
      TextView lbMessage =(TextView)findViewById(R.id.lbStatus); 
      // TODO Auto-generated method stub 
      updateloop: 
      for(;;) 
      {   
      lbMessage.setText("Bytes read: "+CurrByte); 
      Log.d("mree","Bytes read:"+CurrByte); 
       try 
       { 
        Thread.sleep(1000); 
       } 
       catch (InterruptedException e) 
       { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       } 

       if(filelength == CurrByte) 
       { 
        break updateloop; 
       } 
      } 
     } 

    } 

MainActivity 클래스 :

공용 클래스 MainActivity가 ActionBarActivity를 확장 {

String fileurl = "http://images.all-free-download.com/images/graphiclarge/beautiful_christmas_greeting_card_01_vector_180185.jpg"; 

Handler myhandler = new Handler(Looper.getMainLooper()); 
int CurrByte= 0; 
//String fd ="http://www.oracle.com/"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Button btDownload =(Button)findViewById(R.id.btDownload); 
    btDownload.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 

      Thread myThread = new Thread(new DownloadThread()); 
      myThread.start(); 

     } 
    }); 
} 
+0

내가 돈 ' Handler의 사용법이나 runOnUIThread()를 보지 마십시오. – Kao

+0

myhandler.post (new MainActivity.UpdateS (len)), while 루프 이상 – Mree

답변

0

Probabl 이 문제가 있습니다 :

Thread.sleep(1000); 

업데이트되지 않기 때문에 UI 스레드를 차단할 수 없습니다. 이것을 제거하십시오. 또한 클래스에서 for 루프를 제거해야 할 수도 있습니다.

편집 :

가장 좋은 방법은 UI 스레드에서 배경 작업 및 게시 결과를 수행하기 위해 특별히 설계 AsyncTask을 사용하는 것입니다.

Edit2가 :

또 다른 옵션, AsyncTasks를 사용하지 않고 :

귀하의 업데이트 클래스는 다음과 같아야합니다

public class UpdateS implements Runnable { 
    int filelength; 
    Activity context; 

    UpdateS(int len, Activity context) { 
     this.filelength = len; 
     this.context = context; 
    } 

    @Override 
    public void run() { 
     TextView lbMessage = (TextView) findViewById(R.id.lbStatus); 
     updateloop: for (;;) { 

      context.runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        lbMessage.setText("Bytes read: " + CurrByte); 
       } 
      }); 

      Log.d("mree", "Bytes read:" + CurrByte); 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 

      if (filelength == CurrByte) { 
       break updateloop; 
      } 
     } 
    } 

} 

전화를하여 DownloadThread에 :

myhandler.post(new MainActivity.UpdateS(len, MainActivity.this)); 
+0

Thread.sleep (1000)을 제거했으며 스레드가 완료되었지만 Text.log가 정상적으로 작동하면 Textview가 업데이트를 가져옵니다. . – Mree

+0

@Mree 당신은 UI 스레드에서 루프를 실행해서는 안됩니다. 수정 된 코드로이 답변에 대한 수정 사항을 확인하십시오. – Kao

+0

감사합니다. – Mree

관련 문제