为什么播放声音的活动会干扰用户界面?

huangapple go评论70阅读模式
英文:

Why does an activity playing a sound disturb the user interface?

问题

我想在用户点击通知时显示通知并播放声音。当我使用活动播放声音时,它在某种程度上是有效的,就像我在这个问题的回答中所写的那样:https://stackoverflow.com/questions/63961419/how-can-i-create-a-notification-that-plays-an-audio-file-when-being-tapped(在这个问题和答案中还有显示如何创建通知以及我的PlaySoundActivity是什么样子的源代码)。

然而,我意识到,在播放声音时,我的主应用程序的外观会发生变化,而且不关闭应用程序就无法恢复。

我是从“选项卡活动(Tabbed Activity)”项目模板创建我的应用程序的。

这是它启动后的样子:

为什么播放声音的活动会干扰用户界面?

而当我点击声音通知时,它的外观变成了这样(部分内容消失了):

为什么播放声音的活动会干扰用户界面?

有人能解释为什么会发生这种情况吗?使用活动来播放声音是错误的方法吗?但是当我使用服务时它在这里也不起作用,我什么声音都听不到!如何解决这个问题?

英文:

I would like to show a notification and play a sound when the user taps onto that notification. It works somehow when I use an activity to play the sound, as I have written in my own answer to this question: https://stackoverflow.com/questions/63961419/how-can-i-create-a-notification-that-plays-an-audio-file-when-being-tapped (in this question and answer there is also the source code showing how I create the notification and how my PlaySoundActivity looks like.

Yet, I have realized, that while the sound is playing, the appearance of my main application changes and it will not be restored without closing the application.

I have created my application from the "Tabbed Activity" project template.

This is how it looks after being started:

为什么播放声音的活动会干扰用户界面?

And this is how it looks when I have tapped onto the sound notification (the sections are gone):

为什么播放声音的活动会干扰用户界面?

Can anyone explain why this happens? Is it a wrong approach to play sound using an activity? But it does not work here when I use a service, I hear nothing! How to solve that?

答案1

得分: 0

根据Android开发者参考文档,“几乎所有的活动都与用户进行交互,因此Activity类会负责为您创建一个窗口,在窗口中您可以使用setContentView(View)放置您的UI”。

我之前没有这样做。因此,会显示一个新窗口,但没有内容。

播放声音的更好解决方案是使用PlaySoundService(服务!!!)而不是活动。它包含的代码几乎与活动相同,但是挂起的意图是使用PendingIntent.getService(...)而不是PendingIntent.getActivity(...)创建的。使用错误的方法不会导致明显的错误消息,但服务不会按预期工作。

英文:

According to the Android developer reference, "almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View)".

I had not done this. Therefore a new window was displayed, but there was no content.

The better solution for playing a sound is to use a PlaySoundService (service!!!) instead of an activity. It contains almost the same code as an activity would do, but the pending intent is created with PendingIntent.getService(...) instead of PendingIntent.getActivity(...). Using the wrong method does not result in an obvious error message, but the service won't work as expected.

huangapple
  • 本文由 发表于 2020年9月29日 22:03:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/64121268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定