如何在应用程序运行时在状态栏中显示图标,包括在后台? [英] How to show an icon in the status bar when application is running, including in the background?

查看:1038
本文介绍了如何在应用程序运行时在状态栏中显示图标,包括在后台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在应用程序运行时在状态栏中放置一个图标,包括它在后台运行时。我该怎么做?

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?

推荐答案

您应该可以使用Notification和NotificationManager执行此操作。然而,获得有保证的方式来了解您的应用程序何时未运行是困难的部分。

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.

您可以通过执行以下操作来获得您希望的基本功能: / p>

You can get the basic functionality of what you are desiring by doing something like:

Notification notification = new Notification(R.drawable.your_app_icon,
                                             R.string.name_of_your_app, 
                                             System.currentTimeMillis());
notification.flags |= Notification.FLAG_NO_CLEAR
                   | Notification.FLAG_ONGOING_EVENT;
NotificationManager notifier = (NotificationManager)
     context.getSystemService(Context.NOTIFICATION_SERVICE);
notifier.notify(1, notification);

此代码必须位于您确定将在应用程序启动时被触发的位置。可能在您的应用程序的自定义应用程序对象的onCreate()方法中。

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.

然而,之后的事情很棘手。杀死应用程序可以随时进行。因此,您也可以尝试在Application类的onTerminate()中放置一些内容,但不能保证调用它。

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.

((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);

将删除图标所需的内容。

will be what is needed to remove the icon.

这篇关于如何在应用程序运行时在状态栏中显示图标,包括在后台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆