Search code examples
androidrunnable

How to keep active a runnable thread when an activity is closed but destroy the thread when the activity start again


I have a runnable thread in one of my activities, which starts when the activity starts. I want to keep the thread running even when my activity is finished, and I want to destroy the thread when the same activity starts again. Is this possible or do I have to try new approach to achieve my goal?


Solution

  • I would suggest using a service. They live as long as you want them to

    public class MyService extends Service {
    private static final String TAG = "MyService";
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
    
    }
    
    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        //stop thread
    }
    
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        //start thread (again)
    }
    

    }

    You have to declare your service in your manifest

    <service android:enabled="true" android:name=".MyService" />
    

    Start and stop your service with

    startService(new Intent(this, MyService.class));
    stopService(new Intent(this, MyService.class));
    

    If you want to check if your service is running you can use this code

    private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (MyService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
    

    }