当应用程序运行时(包括在后台)如何在状态栏中显示图标?
我想在我的应用程序运行时(包括在后台运行时)在状态栏中放置一个图标。我该怎么做?
I want to put an icon in the status bar when ever my application is running, including when it is running in the background. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该能够使用通知和通知管理器来做到这一点。然而,获得有保证的方法来了解应用程序何时未运行是困难的部分。
您可以通过执行以下操作来获得所需的基本功能:
此代码必须位于您确定应用程序启动时会被解雇的位置。可能在应用程序的自定义应用程序对象的 onCreate() 方法中。
然而,在那之后事情就变得棘手了。应用程序的终止可能随时发生。因此,您也可以尝试在 Application 类的 onTerminate() 中添加一些内容,但不保证会被调用。
将是删除图标所需的内容。
You should be able to do this with Notification and the NotificationManager. However getting a guaranteed way to know when your application is not running is the hard part.
You can get the basic functionality of what you are desiring by doing something like:
This code must be somewhere where you are sure will get fired when your application starts. Possibly in your application's custom Application Object's onCreate() method.
However after that things are tricky. The killing of the application can happen at anytime. So you can try to put something in the onTerminate() of the Application class too, but it's not guaranteed to be called.
will be what is needed to remove the icon.
对于新的 API,您可以使用
NotificationCompat.Builder
-只要您的应用程序正在运行并且有人手动关闭您的应用程序,它就会显示。您随时可以通过致电取消通知 -
For new API you can use
NotificationCompat.Builder
-It will show as long as your application is running and someone manually closes your application. You can always cancel your notification by calling -
查看开发指南“创建状态栏通知” 。
实现仅在应用程序运行时保留图标的目标的一种方法是在
onCreate()
中初始化通知并调用cancel(int)
仅当isFinishing()
返回 true 时。一个例子:
Take a look at the Dev Guide "Creating Status Bar Notifications".
One way to achieve the goal of keeping the icon there only when the application is running is to initialize the notification in
onCreate()
and callcancel(int)
in youronPause()
method only ifisFinishing()
returns true.An example:
它确实有效。
我根据上面的示例创建了一个方法:
应该这样调用:applyStatusBar("Statusbar Test", 10);
It really works.
I created a method out of the example above:
It should be called like: applyStatusBar("Statusbar Test", 10);