Context.startService()Context.bindService()
getSystemService() to gain access to the service, e.g.POWER_SERVICE to get a PowerManager and control power management actions.ALARM_SERVICE to get an AlarmManager and create intents at the time of your choosing.NOTIFICATION_SERVICE to get a NotificationManager and inform the user via device
notificationsLOCATION_SERVICE to get a LocationManager and receive for example location (e.g. GPS)
updates._For more services read the documentation of Context
<service
android:name="MyService"
android:icon="@drawable/icon"
android:label="@string/service_name">
</service>
class MyService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
//TODO do something useful
return Service.START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? {
//TODO for communication return IBinder implementation
return null
}
}
| Option | Description |
|---|---|
| Service.START_STICKY | Service is restarted, if it gets terminated. Intent data passed to the onStartCommand method is null. Used for services which manages their own state and do not depend on the Intent data.Service is not restarted. Used for services which are periodically triggered anyway. The service is only restarted, if the runtime has pending startService() calls since the service termination. |
| Service.START_NOT_STICKY | Service is not restarted. Used for services which are periodically triggered anyway. The service is only restarted, if the runtime has pending startService() calls since the service termination. |
| Service.START_REDELIVER_INTENT | Similar to Service.START_STICKY but the original Intent is re-delivered to the onStartCommand method. |
startService() method to start the service from within your activity// Create an explicit intent
val i = Intent(context, MyService::class.java)
// if needed, add data to the intent
i.putExtra("Param1", "Data for the service")
context.startService(i)
IntentService for asynchronous single tasks in the backgroundpublic class ExampleService extends IntentService {
public ExampleService() {
super("ExampleService");
}
@Override
protected void onHandleIntent(Intent intent) {
int waitTime = (int) intent.getExtras().get("wait_time");
// do work here, e.g. download file
try {
Thread.sleep(waitTime * 1000);
intent.setAction("MYSERVICE_FINISHED_ACTION");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// ...
}
| Event | Description |
|---|---|
Intent.ACTION_BOOT_COMPLETED |
Boot completed. Requires the android.permission.RECEIVE_BOOT_COMPLETED permission |
Intent.ACTION_POWER_CONNECTED |
Power got connected to the device |
Intent.ACTION_POWER_DISCONNECTED |
Power got disconnected from the device |
Intent.ACTION_BATTERY_LOW |
Battery gets low, typically used to reduce activities in your app which consume power |
Intent.ACTION_BATTERY_OKAY |
Battery status good again |
class MyPhoneReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "Incoming phone call", Toast.LENGTH_LONG).show()
}
}
<receiver android:name="MyPhoneReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
registerReceiver(Broadcast receiver, IntentFilter filter)unregisterReceiver()LocalBroadcastManager to send messages within your applicationonResume() method, e.g.Note: The usage of LocalBroadCastManager is not recommended. Modern ways suggest the usage of
LiveData that follows the
observable pattern.
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this)
.registerReceiver(mMessageReceiver, new IntentFilter("my-event"));
}
BroadcastReceiver as usual, e.g.private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
onPause() method, e.g.protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
gradle.build filesendBroadcast(Intent intent), e.g.Intent intent = new Intent();
intent.setAction("my-event");
sendBroadcast(intent);
local broadcast is done by using the method sendBroadcast(Intent intent) of
the LocalBroadcastManager, e.g.Intent intent = new Intent();
intent.setAction("my-event");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);