Service中startForeground(int id, Notification notification)解释(用于进程保活)

官方对该方法的解释

/**
* If your service is started (running through {@link Context#startService(Intent)}), then
* also make this service run in the foreground, supplying the ongoing
* notification to be shown to the user while in this state.
* By default started services are background, meaning that their process won't be given
* foreground CPU scheduling (unless something else in that process is foreground) and,
* 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 use
* {@link #startForeground} 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.
*
* 

Note that calling this method does not put the service in the started state * itself, even though the name sounds like it. You must always call * {@link #startService(Intent)} first to tell the system it should keep the service running, * and then use this method to tell it to keep it running harder.

* * @param id The identifier for this notification as per * {@link NotificationManager#notify(int, Notification) * NotificationManager.notify(int, Notification)}; must not be 0. * @param notification The Notification to be displayed. * * @see #stopForeground(boolean) * * 翻译:如果服务(通过{@link Context#startService(Intent)}运行行)已经启动,那么还可以让这个服务运行在前台,并提供给用户的提供一个通知。可以调用这个方法 * 默认情况下,服务启动后是处于后台的,这意味着不会被前台CPU调度(除非该服务的一部分运行在前台)。如果系统需要杀死他们去释放内存(比如,需要在浏览器中展示一个大的界面),他们是很容易被杀死。 * 如果终止该服务会对用户造成破坏,那么可以调用该方法。比如:该服务正在播放一段背景音乐,用户是不希望停止掉的 * * 注意:调用该方法并不能启动服务,你必须调用startService方法去通知系统让该服务保持运行,然后调用该方法告诉系统更坚固的运行该服务 */ public final void startForeground(int id, Notification notification) { try { mActivityManager.setServiceForeground( new ComponentName(this, mClassName), mToken, id, notification, 0); } catch (RemoteException ex) { } }
  1. 如果服务(通过{@link Context#startService(Intent)}运行行)已经启动,那么还可以让这个服务运行在前台,并提供给用户的提供一个通知。可以调用这个方法
  2. 默认情况下,服务启动后是处于后台的,这意味着不会被前台CPU调度(除非该服务的一部分运行在前台)。如果系统需要杀死他们去释放内存(比如,需要在浏览器中展示一个大的界面),他们是很容易被杀死。
  3. 如果终止该服务会对用户造成破坏,那么可以调用该方法。比如:该服务正在播放一段背景音乐,用户是不希望停止掉的

    注:调用该方法并不能启动服务,你必须调用startService方法去通知系统让该服务保持运行,然后调用该方法告诉系统更坚固的运行该服务

作用:使用该方法可以让后台服务编程前台服务,使服务的优先级变低,不容易被回收掉。可以用来做进程保活。可以让当前进程持有这样一个服务,当当前进程进入后台之后,由于持有前台服务,会使得当前进程的优先级变低。一般情况下,若当前进程不持有前台进程,当前进程进入后台之后优先级为5,若持有前台进程,优先级变为2。使得不容易被回收

你可能感兴趣的:(Android)