首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android -为服务实现startForeground?

Android -为服务实现startForeground?
EN

Stack Overflow用户
提问于 2011-06-19 01:42:10
回答 4查看 216.8K关注 0票数 140

所以我不确定在哪里/如何实现这个方法来让我的服务在前台运行。目前,我在另一个活动中通过以下方式启动我的服务:

代码语言:javascript
复制
Intent i = new Intent(context, myService.class); 
context.startService(i);

然后在myServices的onCreate()中,我尝试了startForeground()...

代码语言:javascript
复制
Notification notification = new Notification();
startForeground(1, notification);

所以,是的,我有点迷茫,不确定如何实现这一点。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-06-19 02:21:31

我会从完全填写Notification开始。演示startForeground()用法的Here is a sample project

票数 140
EN

Stack Overflow用户

发布于 2016-03-16 01:40:17

从您的主活动中,使用以下代码启动服务:

代码语言:javascript
复制
Intent i = new Intent(context, MyService.class); 
context.startService(i);

然后,在您的onCreate()服务中,您将构建通知并将其设置为前台,如下所示:

代码语言:javascript
复制
Intent notificationIntent = new Intent(this, MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.app_icon)
                .setContentTitle("My Awesome App")
                .setContentText("Doing some work...")
                .setContentIntent(pendingIntent).build();

startForeground(1337, notification);
票数 82
EN

Stack Overflow用户

发布于 2015-01-26 11:41:13

这是我将服务设置为前台的代码:

代码语言:javascript
复制
private void runAsForeground(){
    Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
            notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    Notification notification=new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.ic_launcher)
                                .setContentText(getString(R.string.isRecording))
                                .setContentIntent(pendingIntent).build();

    startForeground(NOTIFICATION_ID, notification);

}

我需要使用PendingIntent构建一个通知,这样我就可以从该通知开始我的主要活动。

要删除通知,只需调用stopForeground(True)即可;

它在onStartCommand()中调用。请参考我的代码:https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java

票数 32
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6397754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档