2015-11-01 72 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 
    } 
} 
相关问题