【问题标题】:Displaying an icon in status bar when my task is running当我的任务运行时在状态栏中显示一个图标
【发布时间】:2012-01-12 13:03:10
【问题描述】:

我正在创建一个 android 服务,它将在设备启动过程完成后开始运行。在我的服务中,我正在创建一个任务。此任务将根据某些条件随时启动或停止。我的意图是每当我开始我的任务时,我想在状态栏中显示一个图标以知道我的任务正在运行,就像蓝牙图标打开时会显示一样。

【问题讨论】:

标签: android statusbar


【解决方案1】:

您需要Notification。代码在说话:)

在您的服务中:

private NotificationManager mNM;
private int NOTIFICATION = 10002; //Any unique number for this notification

显示通知:

private void showNotification() {
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.local_service_started);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.status_icon, text, System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent);

    // Send the notification.
    mNM.notify(NOTIFICATION, notification);
}

要隐藏它,您只需这样做:

mNM.cancel(NOTIFICATION); //The same unique notification number.

以下是一些说明:

  • R.drawable.status_icon:通知图标
  • R.string.local_service_started:通知标题
  • R.string.local_service_label:通知最新信息(副标题)
  • MainActivity.class :用户点击通知时将启动的Activity

【讨论】:

  • 我认为通知与状态栏图标不同。我提到了状态栏上显示的蓝牙图标。我认为您的回答不适合我的要求。无论如何感谢您回答我的问题。
  • 您的意思是用户永远不会与之交互的图标?喜欢 3G 图标、同步和耳机?
  • Android源码中有一个类叫StatusBarPolicy.java。在构造函数中,状态栏中可能出现的每个图标都被初始化并设置为可见或不可见(根据需要)。您可以参考this thread了解更多信息。
  • 回答你的问题,我认为除了系统应用之外的应用是不可能的。
【解决方案2】:

您可以使用自定义标题栏,例如 Custom title with image

并检查您的服务启用或禁用的首选项设置并设置自定义标题。但在此之前请阅读:http://developer.android.com/guide/topics/ui/notifiers/notifications.html

【讨论】:

  • 自定义标题与状态栏图标不同。实际上在我的应用程序中没有任何活动,它是设备启动后自动启动的服务。是否可以在应用程序中使用没有活动的自定义标题?无论如何感谢您的回答。
  • 是的,它可以在没有任何活动的情况下启动服务......只需将您的服务作为前台启动。您将提供一个通知对象以启动服务
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多