startService()导致UI线程冻结

时间:2018-04-25 19:28:04

标签: android android-service ui-thread foreground-service

在我的应用程序中,我正在启动前台服务并显示进度对话框以更新用户进度。在某些手机上启动前台服务会导致ui滞后几秒钟。如果我禁用以下代码,则ui响应正常。

启动该服务的代码是applicationContext.startService(FirmwareUpdateService.createUpdateActionIntent(applicationContext, progress));

如果我评论上面的代码,那么没有任何冻结。

如果我评论服务中的逻辑(仅显示前景通知),它就没有区别。

private void createUpdateNotification(int progress) { return new Notification.Builder(this) .setContentTitle(getString(R.string.updating)) .setProgress(MAX_PROGRESS, progress, false) .setSmallIcon(R.drawable.push_notif_icon) .build(); }

Notification notification = createUpdateNotification(progress); startForeground(NOTIFICATION_ID, notification);

第一次启动服务后,顺序调用不会冻结UI。任何见解都表示赞赏!

1 个答案:

答案 0 :(得分:0)

通过使用Binder获取与服务的连接来解决此问题。出于某些原因,较旧的Android手机在使用Intent为同一服务但行动不同而调用startService()时会遇到困难。

编辑: 看起来问题的主要原因不是服务。这是SharedPreferences。我们在SharedPreferences中排队了很多.apply()个。 Android似乎将所有这些更改刷新到磁盘,并且这样做会阻止UI线程。

如果您有很多SharedPreferences .apply()挂起,那么如果您设置应用程序或启动服务,它会阻止UI线程,因为它会将所有更改转储到SharedPreferences。我不确定这是否打算以及Android决定在哪些情况下这样做。

相关问题