小编Ily*_*sis的帖子

从前台服务观察LiveData

我有一个存储库,它包含LiveData对象,并由活动和前台服务通过ViewModel使用.当我开始观察活动时,一切都按预期工作.但是,从服务中观察不会触发观察.这是我使用的代码

class MyService: LifecycleService() {
     lateinit var viewModel: PlayerServiceViewModel

     override fun onCreate() {
          viewModel = MyViewModel(applicationContext as Application)
     }

     override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
          viewModel.getLiveData().observe(this, Observer { data ->
            // Do something with the data
        })
     }
}
Run Code Online (Sandbox Code Playgroud)

任何想法为什么它不起作用,我没有收到数据?

android android-service android-livedata

11
推荐指数
1
解决办法
1万
查看次数

Android通知管理器TransactionTooLargeException

我正在使用具有持续通知的前台服务,该服务非常频繁地更新.

服务启动时,我使用通知构建器初始化通知管理器并保留所有引用.

通知具有带按钮的自定义布局.每次用户按下按钮时,我都会更新远程视图并调用notificationManager.notify(service_id,notificationBuilderCompat.build()).

最后,在多次单击后,我收到TransactionTooLargeException错误,其中包含数据包的大小(以字节为单位).每个notify()都会为此数字添加更多字节.

处理这个问题的最佳方法是什么?

演示使用的代码:

class MyService: LifecycleService() {

var notificationBuilderCompat: NotificationCompat.Builder
var notificationManager: NotificationManager
var viewModel: ViewModel
val FOREGROUND_SERVICE = 10
val EXTRA_NOTIFICATION_TYPE = "EXTRA_NOTIFICATION_TYPE"
val NOTIFICATION_CHANNEL_ID = "channel_01"

override fun onCreate() {
    super.onCreate()

    // View model that holds the data
    viewModel = ViewModel()

    registerReceiver(broadcastReceiver, IntentFilter(NOTIFICATION_MESSAGE_INTENT)
    notificationManager = getSytemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    // In case of android O
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "notification_name", NotificationManager.IMPORTNACE_MAX)
        notificationManager.createNotificationChannel(channel)
    }

    notificationBuilderCompat = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL_ID) …
Run Code Online (Sandbox Code Playgroud)

android android-notifications

5
推荐指数
0
解决办法
587
查看次数