2015-11-01 64 views
-2

我有一個線程。該線程從服務器加載數據並將其設置爲列表視圖。如何取消/停止然後重新啓動在android的線程

我想取消停止線程然後重新啓動這個線程被點擊重啓按鈕時。

我已經使用while(true)並使用interrupt線程和使用stop()但沒有任何工作!

回答

0
public class MyActivity extends Activity { 

private Thread mThread; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 


    mThread = new Thread(){ 
    @Override 
    public void run(){ 
     // Perform thread commands... 
for (int i=0; i < 5000; i++) 
{ 
    // do something... 
} 

// Call the stopThread() method. 
     stopThread(this); 
     } 
    }; 

// Start the thread. 
    mThread.start(); 
} 

private synchronized void stopThread(Thread theThread) 
{ 
if (theThread != null) 
{ 
    theThread = null; 
} 
} 
} 
1

你無法重新啓動一個線程拋出IllegalThreadStateException,如果線程前/

已經啓動停止或啓動線程使用下面的代碼

import android.util.Log; 

public class ThreadingEx implements Runnable { 

    private Thread backgroundThread; 
    private static final String TAG = ThreadingEx.class.getName(); 


    public void start() { 
     if(backgroundThread == null) { 
      backgroundThread = new Thread(this); 
      backgroundThread.start(); 
     } 
    } 

    public void stop() { 
     if(backgroundThread != null) { 
      backgroundThread.interrupt(); 
     } 
    } 

    public void run() { 
     try { 
      Log.i(TAG,"Starting."); 
      while(!backgroundThread.interrupted()) { 
      //To Do 
      } 
      Log.i(TAG,"Stopping."); 
     } catch(Exception ex) { 

      Log.i(TAG,"Exception."+ex); 
     } finally { 
      backgroundThread = null; 
     } 
    } 
} 
0

可以使用字段告訴你的線程停止,重新啓動或取消。

class TheThread extends Thread { 
    private boolean running = true; 

    public void run() { 
     // do this... 
     // do that... 
     // ....... 

     if (!running) return; 

     //Continue your job 
    } 
} 
相關問題