我想让我Service在前台跑步.我尝试使用此示例(请查看" 在前台运行服务 "部分),但startForeground()实际上并未显示我的通知.并没有抛出异常.为了使它显示,我需要使用NotificationManager像这里解释的那样.随着NotificationManager我的通知工作,但我不确定我Service的前景是在这个"无声"呼叫之后startForeground().
有什么不对?
编辑:我刚刚测试了这个应该演示的示例项目startForeground(),但它不起作用!我使用API v7.0,我在模拟器和真实设备(SE Xperia Neo)上测试了它.通知不会出现.
EDIT2:如果我试着打电话,setForeground()那我就收到了警告setForeground: ignoring old API call.
我也尝试使用这里startForegroundCompat()描述的,但效果绝对相同.我按照这里的描述检查我的服务是否是前台服务,我发现我的服务不是前台服务.ActivityManager.RunningServiceInfo
我正在尝试停止作为前台服务运行的服务.
目前的问题是,当我打电话时stopService(),通知仍然存在.
所以在我的解决方案中,我添加了一个我正在注册的接收器 onCreate()
在onReceive()我调用的方法内部stopforeground(true),它隐藏了通知.然后stopself()停止服务.
onDestroy()我在里面注册了接收器.
有没有更合适的方法来处理这个?因为stopService()根本不起作用.
@Override
public void onDestroy(){
unregisterReceiver(receiver);
super.onDestroy();
}
Run Code Online (Sandbox Code Playgroud) 我的前台粘性服务在几个小时后被杀死而没有重新启动.我知道这已被问了几次,我已经阅读并验证了我设备上的所有检查.重要的是要注意,这似乎只发生在华为设备上.
因此,请允许我提供以下详细信息.
定期服务
public class PeriodicService extends Service {
@Override
public void onCreate() {
super.onCreate();
acquireWakeLock();
foregroundify();
}
private void foregroundify() {
// Omitted for brevity. Yes it does starts a foreground service with a notification
// verified with adb shell dumpsys activity processes > tmp.txt
// entry in tmp.txt => "Proc # 1: prcp T/S/SF trm: 0 14790:my.app.package.indentifier/u0a172 (fg-service)"
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
acquireWakeLock();
if (!isServiceRunningInForeground(this, this.getClass())){
foregroundify();
}
PeriodicAlarmManager alarmManager = …Run Code Online (Sandbox Code Playgroud) android alarmmanager foreground-service android-6.0-marshmallow huawei