2012-03-17 5 views
4

비동기 작업에서 새 스레드를 시작할 수 있습니까? 이 같은 뭔가 :비동기 작업에서 새 스레드 시작

public class FirstActivity extends Activity { 

protected ProgressBar progBar; 
protected Intent intent; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    progBar = (ProgressBar)findViewById(R.id.start_progressBar); 
    progBar.setProgress(0); 
    new StartingApp().execute(); 
} 

protected class StartingApp extends AsyncTask<Void, Integer, Void> { 

    int myProgress; 

    @Override 
    protected void onPreExecute() { 
     myProgress = 0; 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 

     while(myProgress<50){ 
      myProgress++; 
      publishProgress(myProgress); 
       SystemClock.sleep(10); 
      } 

     MyRunnableClass mrc = new MyRunnableClass(); 
     mrc.run(); 

     return null;  
    } 

    @Override 
    protected void onPostExecute(Void result){ 

     intent = new Intent(FirstActivity.this, SecondActivity.class); 
     startActivity(intent); 
    } 

    @Override 
    protected void onProgressUpdate(Integer... values) { 

     progBar.setProgress(values[0]); 
    } 
} 
} 

MyRunnableClass는 Runnable를 구현하는 클래스입니다. 첫 번째 작업에서 응용 프로그램이 초기화되는 동안 (진행 데이터 표시 줄, 스레드 시작) 진행 표시 줄을 표시하기 때문에 이런 식으로 싶습니다.

또 다른 질문은 : run() 또는 start() 메서드를 사용해야합니까?

미리 감사드립니다.

+1

'Runnable'을'run()'하면 새 스레드를 얻지 못합니다. 당신은'(new Thread (mrc)). start();'을해야하고 가능하다. 그러나 왜 당신은 스레드에 스레드를 갖고 싶을까? – zapl

+0

진행 상황이 없습니다. 당신은 단지 진전을 시뮬레이션하고 있습니다. 어쩌면 불확실한 진행 표시 줄을 사용해야합니다. – 207

+0

@zapl 그래서 Runnable 클래스에'run()'또는'start()'를 사용하면 정확히 무엇을하고 있습니까? 내 아이디어는 AsnycTask를 사용하여 응용 프로그램의 수명주기 동안 사용 된 작업자 스레드를 시작한 후 다음 작업으로 변경하는 것입니다. – amp

답변

0

왜 하시겠습니까? 코드에서 지적했듯이 새 스레드 (mrc) .start()를 호출하여 작동하게해야합니다. 그렇지 않으면 그 코드에서 새로운 스레드를 생성하는 어떤 문제도 보지 못합니다.

+0

zapl처럼, 그것은 이런 식으로해야합니다 ... 고마워! – amp

관련 문제