Basic IntentService Example
suggest changeThe abstract class IntentService
is a base class for services, which run in the background without any user interface. Therefore, in order to update the UI, we have to make use of a receiver, which may be either a BroadcastReceiver
or a ResultReceiver
:
- A
BroadcastReceiver
should be used if your service needs to communicate with multiple components that want to listen for communication. - A
ResultReceiver
: should be used if your service needs to communicate with only the parent application (i.e. your application).
Within the IntentService
, we have one key method, onHandleIntent()
, in which we will do all actions, for example, preparing notifications, creating alarms, etc.
If you want to use you own IntentService
, you have to extend it as follows:
public class YourIntentService extends IntentService { public YourIntentService () { super("YourIntentService "); }
@Override protected void onHandleIntent(Intent intent) { // TODO: Write your own code here. } }
Calling/starting the activity can be done as follows:
Intent i = new Intent(this, YourIntentService.class); startService(i); // For the service. startActivity(i); // For the activity; ignore this for now.
Similar to any activity, you can pass extra information such as bundle data to it as follows:
Intent passDataIntent = new Intent(this, YourIntentService.class); msgIntent.putExtra("foo","bar"); startService(passDataIntent);
Now assume that we passed some data to the YourIntentService
class. Based on this data, an action can be performed as follows:
public class YourIntentService extends IntentService { private String actvityValue="bar"; String retrivedValue=intent.getStringExtra("foo"); public YourIntentService () { super("YourIntentService "); } @Override protected void onHandleIntent(Intent intent) { if(retrivedValue.equals(actvityValue)){ // Send the notification to foo. } else { // Retrieving data failed. } } }
The code above also shows how to handle constraints in the OnHandleIntent()
method.