Tutorials Android How to create a background service in Android

How to create a background service in Android

To create a background service, first you need to add the service into your manifest file.  Then, create a class that extends service.  Finally, in your activity start the service.

1. First add the following service declaration in your application manifest file.

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

2. Create a new class MyService that extends Service class.

public class MyService extends Service {
  @Override
  public void onCreate() {
  }
 
  @Override
  public void onStart(Intent intent, int startId) {
    //do something
  }
 
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
}

3. To start the service and stop the service:

 
public class MyActivity extends Activity {
  @Override
  public void onCreate() {
    …
    startService(new Intent(this, MyService.class);
  }
 
  @Override
  public void onStop() {
    …
    stopService(new Intent(this, MyService.class));
  }
}
Total
0
Shares
Leave a Reply

Your email address will not be published.

Previous Post

How to access accelerometer in Android

Next Post

How to Monitor TextView Changes in Android

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All