I am referring to android design considerations: AsyncTask vs Service (IntentService?)
According to the discussion, AsyncTask does not suit, because it is tightly "bound" to your Activity
So, I launch a Thread
(I assume AsyncTask and Thread belong to same category), have an infinity running loop in it and did the following testing.
So, I expect after I change from Thread
to Service
, my Service
will keep alive even after I quit or kill my app.
Intent intent = new Intent(this, SyncWithCloudService.class);
startService(intent);
public class SyncWithCloudService extends IntentService {
public SyncWithCloudService() {
super("SyncWithCloudService");
}
@Override
protected void onHandleIntent(Intent intent) {
int i = 0;
while (true) {
Log.i("CHEOK", "Service i is " + (i++));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Log.i("CHEOK", "", ex);
}
}
}
}
// Doesn't matter whether I use "android:process" or not.
<service
android:name="com.xxx.xml.SyncWithCloudService"
android:process=".my_process" >
</service>
However, my finding is that,
It seems that the behaviour of Service
and Thread
are the same. So, why I should use Service
instead of Thread
? Is there anything I had missed out? I thought my Service
suppose to keep running, even after I kill my app?
To stop a IntentService, call the method stopService (Intent service). It request that a given application service be stopped. If the service is not running, nothing happens. Otherwise it is stopped.
First, the easiest way to do what you're trying to do is to launch an Android Broadcast when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart after that. Dear Dr Sabri Allani, If your Service is started by your app then actually your service is running on main process.
IntentService runs on its own thread. It will stop itself when it's done.
IntentService is an extension of the Service component class that handles asynchronous requests (expressed as Intent s) on demand. Clients send requests through Context.
Nope. Service will stop running when you kill your application. When you kill your application all components of it are killed (activities, services, etc.).
In general the behaviour of Thread and Service are similar. However, If you start a Thread from an Activity and then shutdown the activity (ie: quit your application), eventually Android will notice that your process has no active components in it (since Android doesn't recognize your Thread as an active component) and it will just kill your process, thereby killing the thread.
However, if you have a Service running, then Android will notice that you have a service running and not kill it so readily. However, it is still possible that Android will kill your service process if it isn't "in use".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With