最近在使用Android 4.1系统的时候,发现在手机休眠一段时间后(1-2小时),后台运行的服务被强行kill掉,有可能是系统回收内存的一种机制,要想避免这种情况可以通过startForeground让服务前台运行,当stopservice的时候通过stopForeground去掉。

以下是android官方描述:

Running a Service in the Foreground


For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an activity to interact with the music player.

startForeground() . This method takes two parameters: an integer that uniquely identifies the notification and the Notification

Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);

stopForeground() . This method takes a boolean, indicating whether to remove the status bar notification as well. This method does not stop the service. However, if you stop the service while it's still running in the foreground, then the notification is also removed.

startForeground() and stopForeground() were introduced in Android 2.0 (API Level 5). In order to run your service in the foreground on older versions of the platform, you must use the previous setForeground() method—see the startForeground()

Creating Status Bar Notifications.

要想实现需求,我们只需要在onStartCommand里面调用 startForeground,然后再onDestroy里面调用stopForeground即可!

实际情况就譬如手机里面的音乐播放器一样,不管手机如何休眠,只要开始播放音乐了,就不会kill掉这个服务,一旦停止播放音乐,服务就可能被清掉。

FYI

java校验一个对象是否为空 java判断对象是否有值

最近在搞个项目,需要做到请求一个接口,这个接口可能涉及多张表的字段。做一套公共机制,可能直接根据是否上送了某张表的栏位更新对应表的值,没涉及的表则不更新。思路将接口dto采用copy工具,给入到一个个类中,然后判断每个类是否存在有值得属性。public class ObjectUtil { public static boolean hasContent(Object object) {

jquery鼠标移出非当前节点隐藏 jquery移除div标签

原生js删除div先根据id获取对象,然后获取该对象的父节点,根据父节点对象删除对应的子对象 <script type="text/javascript"> var _div= document.getElementById("id"); _div.parentNode.removeChild(_div); </script>Jquery删除div主要