现在的位置: 首页 > 综合 > 正文

Android Service—在前台运行服务

2013年08月09日 ⁄ 综合 ⁄ 共 1012字 ⁄ 字号 评论关闭

前台服务是哪些被认为用户知道的并且在内存低的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,他被放到了“正在进行中(Ongoing)”标题之下,这就意味着直到这个服务被终止或从前台删除通知才能被解除。

例如,一个播放音乐的音乐播放器服务应该被设置在前台运行,因为用户明确的知道它们的操作。状态栏中的通知可能指明了当前的歌曲,并且用户启动一个跟这个音乐播放器交互的Activity。

要让你的服务在前台运行,需要调用startForeground()方法,这个方法需要两个参数:一个唯一标识通知的整数和给状态栏的通知,如:

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);

要从前台删除服务,需要调用stopForeground()方法,这个方法需要一个布尔型参数,指示是否删除状态栏通知。这个方法不终止服务。但是,如果你终止了正在运行的前台服务,那么通知也会被删除。

注意:startForeground()和stopForeground()方法是在Android2.0(API Level 5)中引入的。为了在比较旧的平台版本中运行你的服务,你必须使用以前的setForeground()方法---关于如何提供向后的兼容性,请看startForeground()方法文档。

关于通知的更多信息,请看“创建状态栏通知(Creating Status Bar Notifications)”

抱歉!评论已关闭.