Sunday, 20 November 2016

Background Service: IntentService

A Service is a component which runs in the background, without direct interaction with the user. A service has no user interface as a result of which it is not bound to the lifecycle of an activity. Services are used for repetitive and potential long running operations, checking for new data, data processing, indexing content, etc.

The IntentService class provides a straightforward structure for running an operation on a single background thread. IntentService runs outside the application in a background process, so the process will run even if your application is closed.

- A few limitations of an IntentService:

- You cannot affect the user interface from this background service directly,
- Requests are handled on a single worker thread and processes just one request at a time,
- You cannot easily cancel an intent service once you start one.

- A service can take two states −
  
  Started - A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.

  Bound - A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests and get results.

Implementation:
1. Make a simple class that extends Service class to make it your background service class named as MyService.java

public class MyService extends Service {

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }

   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

2. Now in your MainActivity.java class add the following method to start and stop your service as follows:

public class MainActivity extends Activity {
   String msg = "Test Service : ";

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.d(msg, "The onCreate() event called..!");
   }

   public void startService(View view) {
      startService(new Intent(getApplicationContext(), MyService.class));
   }

   // Method to stop the service
   public void stopService(View view) {
      stopService(new Intent(getApplicationContext(), MyService.class));
   }
}

3. Add the service tag in your AndroidManifest.xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.nishant.backgroundservicesample">

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">

      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>

      <service android:name=".MyService" />

   </application>
</manifest>

That's all. Now run your project and test it.
You can add a timer in your service to prompt you at a certain interval, for example show a simple toast at every 5 minutes through your service. Try it.
Comment if you have any issues.




No comments:

Post a Comment