In the last Article you learnt about Android Services and the difference between a bound and a started service. In this Article you will learn how to call the IntentService you created earlier.
To create a started service you need to extend the IntentService class.
public class SampleService extends IntentService
Let’s take a simple example to illustrate how this works.
In the onHandleIntent method you will add a Log.
@Override protected void onHandleIntent(Intent intent) { Log.v(TAG, "In onHandleIntent. Message will be printed after 10sec"); if (intent != null) { synchronized (this){ try { wait(10000); } catch (InterruptedException e) { e.printStackTrace(); } Log.v(TAG, "Service started"); } } }
To call this service you will add a button to the content_main.xml file
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:layout_margin="15dp" android:id="@+id/callSampleServiceId" android:text="Start Service" android:background="@android:color/holo_blue_dark" android:textColor="@android:color/white"/>
On click of this button an explicit intent will be called.
if(v.getId() == R.id.callSampleServiceId){ Log.v(TAG, "Service Button Clicked"); Intent intent = new Intent(this, SampleService.class); startService(intent); }
View the complete source code here.