【问题标题】:Anndroid : How to send broadcast intent to service from notification action?Android:如何通过通知操作向服务发送广播意图?
【发布时间】:2023-03-10 05:20:01
【问题描述】:

我正在尝试从 Android 上的通知操作中发送广播意图,但在这里有点迷失了。

我有一个 android 服务,它从活动/片段接收广播意图并做出相应的反应,它工作正常,但我不知道如何从通知操作中发送一个。

服务看起来像这样。

class MyService : Service() {

    override fun onCreate() {
        super.onCreate()

        LocalBroadcastManager.getInstance(this).registerReceiver(mIntentActionBroadcastReceiver, IntentFilter(SERVICE_BROADCAST_INTENT))

        val broadcastIntentFilter = IntentFilter()
        broadcastIntentFilter.addAction(SERVICE_BROADCAST_KEY)
        registerReceiver(mIntentActionBroadcastReceiver, broadcastIntentFilter)
    }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // onStart
    }

    private val mIntentActionBroadcastReceiver = object : BroadcastReceiver() {
         override fun onReceive(context: Context, intent: Intent) {
            // do something
        }
    }
}

现在我有了通知通道,用户在其中执行某些操作,看起来像这样。

val notificationBuilder = NotificationCompat.Builder(context, PRIMARY_CHANNEL)
    .addAction(getCustomAction(context))

    private fun getCustomAction(context: Context): NotificationCompat.Action {
        val actionIntent = Intent(context, MyService::class.java).apply {
            action = NOTIFICATION_ACTION_CUSTOM
        }
        val pendingIntent = PendingIntent.getService(context, 0, actionIntent, 0)
        return NotificationCompat.Action(R.drawable.ic_custom_48dp, "", pendingIntent)
    }

当用户点击通知中的动作时,似乎又重新调用了MyService onStartCommand,因此我的服务的某些状态被搞砸了。

相反,是否可以从getCustomAction() 发送广播意图并在服务中接收它并对其进行处理?

getCustomAction() 中会发生这样的事情吗?

val intent = Intent(SERVICE_BROADCAST_INTENT)
intent.putExtra(SERVICE_BROADCAST_KEY,  NOTIFICATION_ACTION_CUSTOM)
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)

【问题讨论】:

    标签: android kotlin service android-service android-notifications


    【解决方案1】:

    是否可以从 getCustomAction() 发送广播意图并在服务中接收它并对其进行处理?

    您可以让服务注册一个系统广播接收器(Context 上的registerReceiver()),然后使用PendingIntent.getBroadcast() 向它发送系统广播(sendBroadcast()Context)以创建PendingIntent

    或者,修复服务以解决“因此我的服务的某些状态被搞砸了”。

    在 getCustomAction() 中可以实现这样的事情吗?

    不,因为发件人是另一个进程,不是你的。 LocalBroadcastManager 仅适用于您自己的进程。

    【讨论】:

    • 感谢您的澄清,您能否分享有关如何将Reciever 注册为服务上下文的示例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多