I have the following code of a service that executes a new thread, in which I want the thread to be terminated after X amount of time (in this case 10s), the problem is that I don't know how to terminate it if I can't call thread methods main, in the new thread. annex code
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.i(getClass().getSimpleName(), "Intent received");
if (workerThread == null || !workerThread.isAlive()) {
Toast.makeText(this, "Servicio en Ejecucion", Toast.LENGTH_SHORT).show();
workerThread = new Thread(new Runnable() {
public void run() {
try {
Log.d("Entró", "si");
Thread.sleep(10000);
//this.stopSelf(); método que deseo ejecutar, pero como es un nuevo hilo no me lo permite
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
workerThread.start();
}
return START_STICKY;
}
Any idea how to achieve this?
You can run on the main thread using runOnUiThread(). Here are some links to the android documentation that explain it quite well in case you need to create a handler from another class and implement it in the main thread.
https://developer.android.com/training/multiple-threads/communicate-ui.html https://developer.android.com/guide/components/processes-and-threads.html