【发布时间】:2012-01-12 13:03:10
【问题描述】:
我正在创建一个 android 服务,它将在设备启动过程完成后开始运行。在我的服务中,我正在创建一个任务。此任务将根据某些条件随时启动或停止。我的意图是每当我开始我的任务时,我想在状态栏中显示一个图标以知道我的任务正在运行,就像蓝牙图标打开时会显示一样。
【问题讨论】:
我正在创建一个 android 服务,它将在设备启动过程完成后开始运行。在我的服务中,我正在创建一个任务。此任务将根据某些条件随时启动或停止。我的意图是每当我开始我的任务时,我想在状态栏中显示一个图标以知道我的任务正在运行,就像蓝牙图标打开时会显示一样。
【问题讨论】:
您需要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【讨论】:
您可以使用自定义标题栏,例如 Custom title with image
并检查您的服务启用或禁用的首选项设置并设置自定义标题。但在此之前请阅读:http://developer.android.com/guide/topics/ui/notifiers/notifications.html
【讨论】: