How to Create a Background Service in Android
Not everything needs to run in a focussed application.
Join the DZone community and get the full member experience.
Join For FreeTo 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));
}
}
Published at DZone with permission of Nilanchala Panigrahy, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments