我有一个长期运行的服务,用于执行某些后台操作。现在,我已经阅读了几个线程,当RAM很低时,Android会考虑杀死这些服务,因为后台LRU缓存必须稍微清理一下以容纳更多页面。所以,我让Android杀了它,我将我的服务数据保存在onTrimMemory回调中(当等级为80时),我希望每次Android杀死我的服务进程之前我都会得到这个回调。但在某些情况下,我没有在onTrimMemory中得到任何回调,我的进程被终止,导致数据丢失。
以下是我的进程被杀之前的日志:
06-15 20:43:18.150 17240 17365 I Icing : Indexing 4C988B73CC982428683ECBAE956EE592EB3D7590 from com.google.android.googlequicksearchbox
06-15 20:43:18.170 888 888 I
ConfigService: onDestroy
06-15 20:43:18.290 17240 17365 I Icing : Not enough disk space for indexing trimmable
06-15 20:43:18.360 584 710 I InputReader: Touch event's action is 0x0 (deviceType=0) [pCnt=1, s=0.213 ] when=2010937946000
06-15 20:43:18.360 584 709 I InputDispatcher: Delivering touch to: action: 0x4, toolType: 1
06-15 20:43:18.360 584 709 I InputDispatcher: Delivering touch to: action: 0x0, toolType: 1
06-15 20:43:18.360 584 709 I InputDispatcher: Delivering touch to: action: 0x0, toolType: 1
06-15 20:43:18.390 584 1075 W ActivityManager: Failed setting oom adj of ProcessRecord{4251b490 17777:com.example.gaurav/u0a137} to 13
06-15 20:43:18.390 584 1075 W ActivityManager: Failed setting oom adj of ProcessRecord{4260cf38 16704:android.process.media/u0a24} to 15
06-15 20:43:18.400 584 1075 I ActivityManager: Killing 17971:com.google.android.apps.docs/u0a60 (adj 11): empty, 17028K
06-15 20:43:18.430 584 927 I ActivityManager: Process com.example.gaurav (pid 17777) (adj 11) has died.
06-15 20:43:18.440 584 927 W ActivityManager: Failed setting oom adj of ProcessRecord{4260cf38 16704:android.process.media/u0a24} to 11
06-15 20:43:18.440 584 885 I ActivityManager: Process android.process.media (pid 16704) (adj 13) has died.
我的进程是com.example.gaurav,并且在我的进程被杀死之前没有onTrimMemory日志。这里的任何人都可以解释这些日志所指示我已经用谷歌搜索,但找不到任何令人信服的东西。 关于前台服务解决方案,我想避免这种情况,因为我的服务长时间运行,并且使其前景消耗大量电池。
@pskink, 这是我服务中的onTrimMemory回调方法:
@Override
public void onTrimMemory(int level) {
// TODO Auto-generated method stub
Log.v(LOG_TAG, "on Trim memory callback, level : " + level);
super.onTrimMemory(level);
if (level >= TRIM_MEMORY_COMPLETE && UsageSharedPrefernceHelper.isServiceRunning(mContext)) {
Log.v(LOG_TAG, "Trim memory level is greater than 80, kill service");
saveDataOnKill();
}
}
另外,我有时会得到日志,例如:
06-15 20:43:46.000 18420 18420 V MyService:on Trim memory callback,level:80
所以,这并不是因为缺少日志。