所以我不确定在哪里/如何实现这个方法来让我的服务在前台运行。目前,我在另一个活动中通过以下方式启动我的服务:
Intent i = new Intent(context, myService.class);
context.startService(i);
然后在myServices的onCreate()中,我尝试了startForeground()...
Notification notification = new Notification();
startForeground(1, notification);
所以,是的,我有点迷茫,不确定如何实现这一点。
发布于 2011-06-19 02:21:31
我会从完全填写Notification
开始。演示startForeground()
用法的Here is a sample project。
发布于 2016-03-16 01:40:17
从您的主活动中,使用以下代码启动服务:
Intent i = new Intent(context, MyService.class);
context.startService(i);
然后,在您的onCreate()
服务中,您将构建通知并将其设置为前台,如下所示:
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);
发布于 2015-01-26 11:41:13
这是我将服务设置为前台的代码:
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
https://stackoverflow.com/questions/6397754
复制相似问题