2016-04-28 11 views

Antwort

2

Sie können diesen einfachen Code versuchen:

final volatile boolean toExit = false; 
    final Thread t = new Thread(new Runnable() { 

     @Override 
     public void run() { 
      while(!toExit){ 
       // Your code 
       Thread.sleep(100); 
      } 
     } 
    }); 

    findViewById(R.id.button1).setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      t.start(); 
     } 
    }); 

    findViewById(R.id.button2).setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      toExit = true; 
     } 
    }); 

Der Faden wird gestoppt, nachdem button2 auf while(!toExit) geklickt und ausführen.

0

Threadstoppmethode ist veraltet. Die beste Lösung wird eine boolesche Variable in der run-Methode haben.

Ihr Thema:

public class MyThread implements Runnable { 

private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class); 
private volatile boolean running = true; 

public void terminate() { 
    running = false; 
} 

@Override 
public void run() { 
    while (running) { 
     try { 
      //Your code that needs to be run multiple times 

      LOGGER.debug("Processing"); 
     } catch (InterruptedException e) { 
      LOGGER.error("Exception", e); 
      running = false; 
     } 
    } 

} 
} 

In Ihrer Aktivität:

MyThread t=new Thread(); 


findViewById(R.id.button1).setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View arg0) { 
     t.start(); 
    } 
}); 

findViewById(R.id.button2).setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 
     t.terminate(); 
    } 
}); 
0

Einsatz unter

-Code
public class SomeBackgroundProcess implements Runnable { 

Thread backgroundThread; 

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("Thread starting."); 
     while(!backgroundThread.interrupted()) { 
      doSomething(); 
     } 
     Log.i("Thread stopping."); 
    } catch(InterruptedException ex) { 
     // important you respond to the InterruptedException and stop processing 
     // when its thrown! Notice this is outside the while loop. 
     Log.i("Thread shutting down as it was requested to stop."); 
    } finally { 
     backgroundThread = null; 
    } 
} 

Hope this helfen Ihnen

Verwandte Themen