运行任务时在状态栏显示图标

5

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


2个回答

7
你需要一个通知(Notification)。代码在表达:)
在你的服务(Service)中:
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)

我认为通知与状态栏图标是不同的。我提到了像蓝牙图标显示在状态栏上的情况。我认为你的回答并不适合我的需求。无论如何,感谢您回答我的问题。 - Yugandhar Babu
你的意思是像用户永远不会与之交互的图标吗?就像3G图标、同步和耳机一样? - iTurki
1
Android源代码中有一个名为StatusBarPolicy.java的类。在构造函数中,初始化并设置了可能出现在状态栏中的每个图标的可见性(根据需要)。您可以参考此线程获取更多信息。 - iTurki
回答你的问题,我认为除了系统应用程序之外,其他应用程序不可能实现。 - iTurki

0

自定义标题与状态栏图标不同。实际上,在我的应用程序中没有活动,它是在设备启动后自动启动的服务。是否可能在应用程序中不使用活动而使用自定义标题?无论如何,感谢您的答复。 - Yugandhar Babu
是的,完全可以在没有任何活动的情况下启动服务...只需将您的服务作为前台启动。您需要提供一个通知对象以启动服务。 - waqaslam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接