Build 1.0_r1(from source)

android.app
Class Service

java.lang.Object
  extended by android.content.Context
      extended by android.content.ContextWrapper
          extended by android.app.Service
All Implemented Interfaces:
ComponentCallbacks

public abstract class Service
extends ContextWrapper
implements ComponentCallbacks

A Service is an application component that runs in the background, not interacting with the user, for an indefinite period of time. Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in the Threading section of the Application Model overview.

The Service class is an important part of an application's overall lifecycle.

Topics covered here:

  1. Service Lifecycle
  2. Permissions
  3. Process Lifecycle

Service Lifecycle

There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStart(android.content.Intent, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStart()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStart(). The client will receive the IBinder object that the service returns from its onBind(android.content.Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder). Usually the IBinder returned is for a complex interface that has been written in aidl.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

Permissions

Global access to a service can be enforced when it is declared in its manifest's <service> tag. By doing so, other applications will need to declare a corresponding <uses-permission> element in their own manifest to be able to start, stop, or bind to the service.

In addition, a service can protect individual IPC calls into it with permissions, by calling the ContextWrapper.checkCallingPermission(java.lang.String) method before executing the implementation of that call.

See the Security Model document for more information on permissions and security in general.

Process Lifecycle

The Android system will attempt to keep the process hosting a service around as long as the service has been started or has clients bound to it. When running low on memory and needing to kill existing processes, the priority of a process hosting the service will be the higher of the following possibilities:

Note this means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. If this happens, the system will later try to restart the service. An important consequence of this is that if you implement onStart() to schedule work to be done asynchronously or in another thread, then you may want to write information about that work into persistent storage during the onStart() call so that it does not get lost if the service later gets killed.

Other application components running in the same process as the service (such as an Activity) can, of course, increase the importance of the overall process beyond just the importance of the service itself.


Field Summary
 
Fields inherited from class android.content.Context
ACTIVITY_SERVICE, ALARM_SERVICE, AUDIO_SERVICE, BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BLUETOOTH_SERVICE, CLIPBOARD_SERVICE, CONNECTIVITY_SERVICE, CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, KEYGUARD_SERVICE, LAYOUT_INFLATER_SERVICE, LOCATION_SERVICE, MODE_APPEND, MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, NOTIFICATION_SERVICE, POWER_SERVICE, SEARCH_SERVICE, SENSOR_SERVICE, STATUS_BAR_SERVICE, TELEPHONY_SERVICE, VIBRATOR_SERVICE, WALLPAPER_SERVICE, WIFI_SERVICE, WINDOW_SERVICE
 
Constructor Summary
Service()
           
 
Method Summary
 void attach(Context context, ActivityThread thread, String className, IBinder token, Application application, Object activityManager)
           
protected  void dump(FileDescriptor fd, PrintWriter writer, String[] args)
          Print the Service's state into the given stream.
protected  void finalize()
          Called by the virtual machine when there are no longer any (non-weak) references to the receiver.
 Application getApplication()
          Return the application that owns this service.
(package private)  String getClassName()
           
abstract  IBinder onBind(Intent intent)
          Return the communication channel to the service.
 void onConfigurationChanged(Configuration newConfig)
          Called by the system when the device configuration changes while your component is running.
 void onCreate()
          Called by the system when the service is first created.
 void onDestroy()
          Called by the system to notify a Service that it is no longer used and is being removed.
 void onLowMemory()
          This is called when the overall system is running low on memory, and would like actively running process to try to tighten their belt.
 void onRebind(Intent intent)
          Called when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(android.content.Intent).
 void onStart(Intent intent, int startId)
          Called by the system every time a client explicitly starts the service by calling Context.startService(android.content.Intent), providing the arguments it supplied and a unique integer token representing the start request.
 boolean onUnbind(Intent intent)
          Called when all clients have disconnected from a particular interface published by the service.
 void setForeground(boolean isForeground)
          Control whether this service is considered to be a foreground service.
 void stopSelf()
          Stop the service, if it was previously started.
 void stopSelf(int startId)
          Old version of stopSelfResult(int) that doesn't return a result.
 boolean stopSelfResult(int startId)
          Stop the service, if the most recent time it was started was startId.
 
Methods inherited from class android.content.ContextWrapper
attachBaseContext, bindService, checkCallingOrSelfPermission, checkCallingOrSelfUriPermission, checkCallingPermission, checkCallingUriPermission, checkPermission, checkUriPermission, checkUriPermission, clearWallpaper, createPackageContext, databaseList, deleteDatabase, deleteFile, enforceCallingOrSelfPermission, enforceCallingOrSelfUriPermission, enforceCallingPermission, enforceCallingUriPermission, enforcePermission, enforceUriPermission, enforceUriPermission, fileList, getApplicationContext, getAssets, getBaseContext, getCacheDir, getClassLoader, getContentResolver, getDatabasePath, getDir, getFilesDir, getFileStreamPath, getMainLooper, getPackageCodePath, getPackageManager, getPackageName, getPackageResourcePath, getResources, getSharedPreferences, getSystemService, getTheme, getWallpaper, getWallpaperDesiredMinimumHeight, getWallpaperDesiredMinimumWidth, grantUriPermission, openFileInput, openFileOutput, openOrCreateDatabase, peekWallpaper, registerReceiver, registerReceiver, removeStickyBroadcast, revokeUriPermission, sendBroadcast, sendBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendStickyBroadcast, setTheme, setWallpaper, setWallpaper, startActivity, startInstrumentation, startService, stopService, unbindService, unregisterReceiver
 
Methods inherited from class android.content.Context
getString, getString, getText, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Service

public Service()
Method Detail

getApplication

public final Application getApplication()
Return the application that owns this service.


onCreate

public void onCreate()
Called by the system when the service is first created. Do not call this method directly. If you override this method, be sure to call super.onCreate().


onStart

public void onStart(Intent intent,
                    int startId)
Called by the system every time a client explicitly starts the service by calling Context.startService(android.content.Intent), providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly. If you override this method, be sure to call super.onStart().

Parameters:
intent - The Intent supplied to Context.startService(android.content.Intent), as given.
startId - A unique integer representing this specific request to start. Use with stopSelfResult(int).
See Also:
stopSelfResult(int)

onDestroy

public void onDestroy()
Called by the system to notify a Service that it is no longer used and is being removed. The service should clean up an resources it holds (threads, registered receivers, etc) at this point. Upon return, there will be no more calls in to this Service object and it is effectively dead. Do not call this method directly. If you override this method, be sure to call super.onDestroy().


onConfigurationChanged

public void onConfigurationChanged(Configuration newConfig)
Description copied from interface: ComponentCallbacks
Called by the system when the device configuration changes while your component is running. Note that, unlike activities, other components are never restarted when a configuration changes: they must always deal with the results of the change, such as by re-retrieving resources.

At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.

Specified by:
onConfigurationChanged in interface ComponentCallbacks
Parameters:
newConfig - The new device configuration.

onLowMemory

public void onLowMemory()
Description copied from interface: ComponentCallbacks
This is called when the overall system is running low on memory, and would like actively running process to try to tighten their belt. While the exact point at which this will be called is not defined, generally it will happen around the time all background process have been killed, that is before reaching the point of killing processes hosting service and foreground UI that we would like to avoid killing.

Applications that want to be nice can implement this method to release any caches or other unnecessary resources they may be holding on to. The system will perform a gc for you after returning from this method.

Specified by:
onLowMemory in interface ComponentCallbacks

onBind

public abstract IBinder onBind(Intent intent)
Return the communication channel to the service. May return null if clients can not bind to the service. The returned IBinder is usually for a complex interface that has been described using aidl.

Note that unlike other application components, calls on to the IBinder interface returned here may not happen on the main thread of the process. More information about this can be found in the Threading section of the Application Model overview.

Parameters:
intent - The Intent that was used to bind to this service, as given to Context.bindService. Note that any extras that were included with the Intent at that point will not be seen here.
Returns:
Return an IBinder through which clients can call on to the service.

onUnbind

public boolean onUnbind(Intent intent)
Called when all clients have disconnected from a particular interface published by the service. The default implementation does nothing and returns false.

Parameters:
intent - The Intent that was used to bind to this service, as given to Context.bindService. Note that any extras that were included with the Intent at that point will not be seen here.
Returns:
Return true if you would like to have the service's onRebind(android.content.Intent) method later called when new clients bind to it.

onRebind

public void onRebind(Intent intent)
Called when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(android.content.Intent). This will only be called if the implementation of onUnbind(android.content.Intent) was overridden to return true.

Parameters:
intent - The Intent that was used to bind to this service, as given to Context.bindService. Note that any extras that were included with the Intent at that point will not be seen here.

stopSelf

public final void stopSelf()
Stop the service, if it was previously started. This is the same as calling Context.stopService(android.content.Intent) for this particular service.

See Also:
stopSelfResult(int)

stopSelf

public final void stopSelf(int startId)
Old version of stopSelfResult(int) that doesn't return a result.

See Also:
stopSelfResult(int)

stopSelfResult

public final boolean stopSelfResult(int startId)
Stop the service, if the most recent time it was started was startId. This is the same as calling Context.stopService(android.content.Intent) for this particular service but allows you to safely avoid stopping if there is a start request from a client that you haven't yet see in onStart(android.content.Intent, int).

Parameters:
startId - The most recent start identifier received in onStart(android.content.Intent, int).
Returns:
Returns true if the startId matches the last start request and the service will be stopped, else false.
See Also:
stopSelf()

setForeground

public final void setForeground(boolean isForeground)
Control whether this service is considered to be a foreground service. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm. You can set this flag if killing your service would be disruptive to the user: such as if your service is performing background music playback, so the user would notice if their music stopped playing.

Parameters:
isForeground - Determines whether this service is considered to be foreground (true) or background (false).

dump

protected void dump(FileDescriptor fd,
                    PrintWriter writer,
                    String[] args)
Print the Service's state into the given stream.

Parameters:
fd - The raw file descriptor that the dump is being sent to.
writer - The PrintWriter to which you should dump your state. This will be closed for you after you return.
args - additional arguments to the dump request.

finalize

protected void finalize()
                 throws Throwable
Description copied from class: Object
Called by the virtual machine when there are no longer any (non-weak) references to the receiver. Subclasses can use this facility to guarantee that any associated resources are cleaned up before the receiver is garbage collected. Uncaught exceptions which are thrown during the running of the method cause it to terminate immediately, but are otherwise ignored.

Note: The virtual machine assumes that the implementation in class Object is empty.

Overrides:
finalize in class Object
Throws:
Throwable - The virtual machine ignores any exceptions which are thrown during finalization.

attach

public final void attach(Context context,
                         ActivityThread thread,
                         String className,
                         IBinder token,
                         Application application,
                         Object activityManager)

getClassName

final String getClassName()

Build 1.0_r1(from source)

Please submit a feedback, bug or feature