Service API changes starting with Android 2.0
Watching developers ingest the Android papers the last assemblage has shown a sort of pain areas in the Service API as substantially as ontogeny issues in the ways services operate. As a result, Android 2.0 introduced a sort of changes and improvements in this area for both developers and users.
The threesome essential changes to be aware of are:
- Service.setForeground() is today deprecated and in 2.0 does nothing.
- There were whatever edge cases in the assist lifecycle that prefabricated it rattling cushy to unexpectedly yield a assist running; newborn APIs in 2.0 attain this such easier to tending with.
- Android 2.0 also introduces a newborn UI for end users to guardian and curb the streaming services on their device.
Background on services
Before feat into the info of 2.0, it haw be multipurpose to go over a quick summary of services. The Service API in Android is one of the key mechanisms for applications to do impact in the background. Due to the artefact Android is designed, erst an covering is no individual circumpolar to the individual it is mostly thoughtful expendable and a politician to be killed by the grouping if it ever needs module elsewhere. The essential artefact applications intend around this is by starting a Service component, which explicitly tells the grouping that they are doing whatever valuable impact and would prefer that the grouping not blackball their impact if it doesn't genuinely requirement to.
This is a rattling coercive artefact but along with that noesis comes whatever responsibility: an actively streaming assist is taking resources absent from another things that crapper separate (including indolent processes in the scenery that don't requirement to be initialized the incoming instance the individual visits them). It is thus essential that developers take tending when artful their services that they exclusive separate when genuinely needed and avoid whatever bugs where they haw unexpectedly yield the assist streaming for daylong durations.
Redesigning Service.setForeground()
During the test standardisation punctuation of Android 1.6 we started to wager more issues cod to an increasing sort of applications using the Service.setForeground() API when they shouldn't be. This is an API that we haven't advertised such because it should not be used by most applications and crapper be rattling hornlike on the system: it asks that the service's impact be aerated as in the foreground, essentially making it unkillable and thus more arduous for the grouping to meliorate from low module situations.
At that point in 1.6 it was likewise New to attain whatever significant changes to the activity here, but in 2.0 we hit finished so: Service.setForeground() today does nothing. The API was ever witting to be something a assist would do in conjunction with putting up an current asking for the user; by saying you are in the foreground, the individual should be "aware" that the assist is streaming in whatever artefact and know how to kibosh it. Thus in locate of the older API Andriod 2.0 introduces digit newborn APIs that require a asking go along with existence in the foreground:
open test vacuum startForeground(int id, Notification notification); open test vacuum stopForeground(boolean removeNotification);This also not coincidentally makes it such easier to curb the asking state along with the service, since the grouping crapper today guarantee that there is ever a asking patch the assist is in the foreground, and that the asking goes absent whenever the assist does.
Many developers module poverty to indite a assist that works on senior platforms as substantially as 2.0 and later; this crapper be realised by using something same the following cipher to selectively call the newborn APIs when they are available.
clannish static test Class[] mStartForegroundSignature = newborn Class[] { int.class, Notification.class}; clannish static test Class[] mStopForegroundSignature = newborn Class[] { boolean.class}; clannish NotificationManager mNM; clannish Method mStartForeground; clannish Method mStopForeground; clannish Object[] mStartForegroundArgs = newborn Object[2]; clannish Object[] mStopForegroundArgs = newborn Object[1]; @Override open vacuum onCreate() { mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); essay { mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature); mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature); } grownup (NoSuchMethodException e) { // Running on an senior platform. mStartForeground = mStopForeground = null; } } /** * This is a cloak around the newborn startForeground method, using the senior * APIs if it is not available. */ vacuum startForegroundCompat(int id, Notification notification) { // If we hit the newborn startForeground API, then ingest it. if (mStartForeground != null) { mStartForegroundArgs[0] = Integer.valueOf(id); mStartForegroundArgs[1] = notification; essay { mStartForeground.invoke(this, mStartForegroundArgs); } grownup (InvocationTargetException e) { // Should not happen. Log.w("MyApp", "Unable to advert startForeground", e); } grownup (IllegalAccessException e) { // Should not happen. Log.w("MyApp", "Unable to advert startForeground", e); } return; } // Fall backwards on the older API. setForeground(true); mNM.notify(id, notification); } /** * This is a cloak around the newborn stopForeground method, using the senior * APIs if it is not available. */ vacuum stopForegroundCompat(int id) { // If we hit the newborn stopForeground API, then ingest it. if (mStopForeground != null) { mStopForegroundArgs[0] = Boolean.TRUE; essay { mStopForeground.invoke(this, mStopForegroundArgs); } grownup (InvocationTargetException e) { // Should not happen. Log.w("MyApp", "Unable to advert stopForeground", e); } grownup (IllegalAccessException e) { // Should not happen. Log.w("MyApp", "Unable to advert stopForeground", e); } return; } // Fall backwards on the older API. Note to equilibrate BEFORE changing the // foreground state, since we could be killed at that point. mNM.cancel(id); setForeground(false); }Service lifecycle changes
Another position we were progressively seeing in 1.6 was that, modify ignoring the services that unsuitably attain themselves foreground, we had a ontogeny sort of devices with a super sort of services streaming in the scenery every fighting apiece another over the acquirable memory.
Part of this difficulty is services that are streaming more than they should or there exclusive existence likewise such clog disagreeable to be finished on the device. However, we also found whatever issues in the interaction between services and the papers that prefabricated it cushy for an covering to yield a assist streaming modify when it is disagreeable to do the correct thing. Consider this exemplary scenario:
Now the assist module sit there created, not realizing it used to be doing whatever work, and so not lettered it should kibosh itself at whatever point.
To come this, in Android 2.0 Service.onStart() as been deprecated (though ease exists and operates as it used to in previous versions of the platform). It is replaced with a newborn Service.onStartCommand() asking that allows the assist to meliorate curb how the grouping should curb it. The key conception here is a newborn termination cipher returned by the function, telling the grouping what it should do with the assist if its impact is killed patch it is running:
- START_STICKY is basically the same as the previous behavior, where the assist is left "started" and module after be restarted by the system. The exclusive difference from previous versions of the papers is that it if it gets restarted because its impact is killed, onStartCommand() module be titled on the incoming happening of the assist with a invalid Intent instead of not existence titled at all. Services that ingest this mode should ever analyse for this housing and tending with it appropriately.
- START_NOT_STICKY says that, after returning from onStartCreated(), if the impact is killed with no remaining move commands to deliver, then the assist module be obstructed instead of restarted. This makes a aggregation more significance for services that are witting to exclusive separate patch executing commands dispatched to them. For example, a assist haw be started every 15 transactions from an alarm to poll whatever network state. If it gets killed patch doing that work, it would be prizewinning to meet permit it be obstructed and intend started the incoming instance the alarm fires.
- START_REDELIVER_INTENT is same START_NOT_STICKY, eliminate if the service's impact is killed before it calls stopSelf() for a presented intent, that aim module be re-delivered to it until it completes (unless after whatever sort of more tries it ease can't complete, at which point the grouping gives up). This is multipurpose for services that are receiving commands of impact to do, and poverty to attain trusty they do yet rank the impact for apiece command sent.
For sympathy with existing applications, the choice return cipher for applications that are targeting an early edition of the papers is a primary START_STICKY_COMPATIBILITY cipher that provides the older activity of not calling onStart() with a invalid intent. Once you move targeting API edition 5 or later, the choice mode is START_STICKY and you staleness be embattled to tending with onStart() or onStartCommand() existence titled with a invalid Intent.
You crapper also easily indite a Service that uses both the older and newborn APIs, depending on the platform. All you requirement to do is attain against the 2.0 SDK with this code:
// This is the older onStart method that module be titled on the pre-2.0 // platform. On 2.0 or after we override onStartCommand() so this // method module not be called. @Override open vacuum onStart(Intent intent, int startId) { handleStart(intent, startId); } @Override open int onStartCommand(Intent intent, int flags, int startId) { handleStart(intent, startId); return START_NOT_STICKY; } vacuum handleStart(Intent intent, int startId) { // do impact }New "running services" individual interface
Our test issue to come is the housing where there are exclusive likewise whatever assist streaming in the amount of module acquirable on a device. This haw be cod to bugs or design flaws in installed applications, or the individual exclusive disagreeable to do likewise much. Historically users hit had no saliency into what is feat on at this take in the system, but it has embellish essential to guy this, at small for lower-end devices, as the ingest of services has had an increasing impact on the individual experience.
To support come this, Android 2.0 introduces a newborn "Running Services" activity acquirable from the Application grouping settings. When brought up, it looks something same this:

The essential content is a itemize of every streaming services that haw be of interest to the user, organized by the processes they separate in. In the warning here, we wager threesome services:
- GTalkService is conception of the accepted Google covering suit; it is streaming in Google's "gapps" process, which currently consumes 6.8MB. It has been started for 3 hours 55 minutes, which on this figure is the instance from when it was first booted.
- ActivityService is conception of the Phonebook app, and its impact consumes 4MB. This also has been streaming since boot.
- SoftKeyboard is a ordinal party signaling method. It has been streaming since I switched to it, most 4 transactions ago.
The individual crapper tap on whatever of these services to curb it; for normal services that are streaming because they were explicitly started, this module present a talking allowing the individual to explicitly kibosh it:

Some another services, same the signaling method, are streaming for another reasons. For these, tapping on the assist module go to the corresponding UI to curb it (in this housing the system's signaling settings).
Finally, along the bottom of the screen are whatever obscure numbers. If you know how to see them, this gives you a aggregation of information on the module position of your device:
- Avail: 38MB+114MB in 25 says that the figure has 38MB of completely liberated (or probable used for unrequired caches) memory, and has another 114MB of acquirable module in 25 scenery processes it crapper blackball at whatever time.
- Other: 32MB in 3 says that the figure has 32MB of unavailable module in 3 unkillable processes (that is, processes that are currently thoughtful to be foreground and staleness be kept running)
For most users, this newborn individual interface should be a such more effective artefact to curb the scenery applications on their figure than the existing "task killer" applications. In the vast majority of cases the reason for a andante streaming figure is likewise whatever services disagreeable to run. This prevents the grouping from existence able to separate whatever scenery processes (which speed up app switching), and ultimately crapper termination in drubbing finished the services when not modify they crapper every be kept running. The Running Services UI is witting to wage rattling specific information most the services that are running, to support attain a good selection most what should be stopped. It also does not ingest the API to obligate kibosh an application, which crapper unintentionally fortuity applications in numerous ways.
For developers, this is an essential agency to secure your services are substantially behaved. As you develop your app, be trusty to keep an eye on Running Services to secure that you are not unexpectedly leaving your services streaming when they shouldn't be. You should also today keep in nous that users haw freely kibosh whatever of your services as they wish, without your control, and statement for that.
Android's Services are a rattling coercive tool, but one of the essential and subtle ways that covering developers crapper alteration the coverall experience a individual has with their phone.
Generated by best funky, gaul abizz.
Powered by Mas BAsy.
Technorati
Tidak ada komentar:
Posting Komentar