简体   繁体   English

如何将意图发送到正在运行的服务或后台活动?

[英]How to send intent to running service or background activity?

I am deveoping a music player in Android right now and am currently stuck with the Notification.我现在正在 Android 中开发一个音乐播放器,目前我被通知卡住了。 I added three Actions to the Notification for Previous, Play/Pause and Next.我为上一个、播放/暂停和下一个的通知添加了三个操作。 Each action needs a PendingIntent to be execute if these buttons are clicked.如果单击这些按钮,则每个操作都需要执行 PendingIntent。

My app is currently build that there is a MainActivity and a Service, which to playback the loaded audio files.我的应用程序目前正在构建有一个 MainActivity 和一个服务,用于播放加载的音频文件。 The Main activity communicates through a reference to the service to do actions like next song and such. Main 活动通过对服务的引用进行通信,以执行下一首歌曲等操作。

What I want to achieve with the actions on the Notifications is that an intent is send to either the service itself, but without starting it or to the MainActivity but without bringing it back to the foreground if its currently in the background.我想通过通知上的操作来实现一个意图是发送到服务本身,但不启动它或发送到 MainActivity,但如果它当前在后台,则不将其带回前台。 So that either the service can control that action itself or let the MainActivity call the appropriate method.这样服务可以自己控制该操作,或者让 MainActivity 调用适当的方法。

After some research I found some people doing that with Broadcast Receivers, but as far as I understand it Broadcasts are send to any suitable application, which i definietly dont want.经过一些研究,我发现有些人使用广播接收器这样做,但据我所知,广播被发送到任何合适的应用程序,我绝对不想要。 I also am not able to find some piece of documentation or similar that points toward a solution.我也找不到一些指向解决方案的文档或类似文件。

What is the best way to do this?做这个的最好方式是什么?

Any help is appreciated!任何帮助表示赞赏!

... but as far as I understand it Broadcasts are send to any suitable application ...但据我了解,广播被发送到任何合适的应用程序

If you use an explicit Intent for your BroadcastReceiver like they do in the guide on creating a Notification then you can be sure that no other component will receive the broadcast (code snippet copied from there):如果您像在创建通知指南中那样为您的BroadcastReceiver使用显式Intent ,那么您可以确定没有其他组件将接收广播(从那里复制的代码片段):

Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);

So it looks like this is the way to go: have your BroadcastReceiver instance decide which component of your app should take control.所以看起来这是通往 go 的方法:让您的BroadcastReceiver实例决定您的应用程序的哪个组件应该控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM