create and execute IntentService in android . Intent service in android .
To send data from intentservice to the UI thread , you can create a custom broadcast & receive the custom broadcast inside the any other class , then fetch the data from intent.
-----------------------------------------------------------------------
Intentservice extends StartedService and does all the handler and looper stuff in the background by itself. Unlike Started service we dont need to create a new worker thread.
step2] we only need to override th onHandleintent() method
All the service lifecycle methods run in Main thread , but the code in the onHandleIntent() method, runs on the worker thread.
public MyIntentService() {
super("MyIntentService");
//This restarts the service is the app is terminated.
setIntentRedelivery(true);
}
@Override
public void onCreate() {
super.onCreate();
Log.d("Keyy","Oncreate executed " + "Thread : " + Thread.currentThread().getName());
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("Keyy","This is from intent service." + "Thread : " + Thread.currentThread().getName());
for (int i=0;i<10;i++){
try {
Thread.sleep(1000);
Log.d("keyy","Counter : " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Keyy","OnDestroy executed " + "Thread : " + Thread.currentThread().getName());
}
}
step3] Use the setIntentredelivery() as true if you want the service to restart if the app is destroyed
before the completion of service.
NO need to use stopself() or stopservice() method as the service automatically closes after completion.
All the major tasks of startedservice is done internally.
since IntentService extends StartedService , the Ibind() method internally returns null here too.
After API 25 or Android oreo , Intentservice wasnt much appreciated to use due to a better alternative called JOBINTENTSERVICE. Due to the background restrictions after android api 25 , it is best suited to use JOBINTENTSERVICE.
--------------------------------------------------------------------------------------------------------------
How to create Intentservice before and after Android oreo .


Comments
Post a Comment