Essential Android IntentService edit forum

Basic IntentService Example

The 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:

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.


Table Of Contents
39 ACRA
64 Menu
112 Loader
119 Xposed
132 Colors
135 Fresco
139 IntentService
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close