Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

publicclassMyServiceextendsService {
privatestatic final StringTAG = "MyService";

@Overridepublic IBinder onBind(Intent intent) {
    returnnull;
}

@OverridepublicvoidonCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

}

@OverridepublicvoidonDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    //stop thread
}

@OverridepublicvoidonStart(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

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

Start and stop your service with

startService(newIntent(this, MyService.class));
stopService(newIntent(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())) {
        returntrue;
    }
}
returnfalse;

}

Post a Comment for "How To Keep Active A Runnable Thread When An Activity Is Closed But Destroy The Thread When The Activity Start Again"