如何确认服务是前台服务

时间:2018-10-21 07:04:03

标签: java android foreground

我有一个播放音乐的服务(媒体播放器),并且运行正常。

  1. 如何重新确认此服务是前台服务?
  2. 如何模拟系统负载并检查服务是否将被终止?

    这是我的代码。

    public int onStartCommand(意图意图,int标志,int startId){                initMediaSession();                 initMediaPlayer();             buildNotification(PlaybackStatus.PLAYING);
            返回super.onStartCommand(intent,flags,startId);     }

    private void buildNotification(PlaybackStatusplayingStatus){

    std::shared_ptr

    }

1 个答案:

答案 0 :(得分:0)

private boolean isServiceRunning(String serviceName){
boolean serviceRunning = false;
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> l = am.getRunningServices(50);
Iterator<ActivityManager.RunningServiceInfo> i = l.iterator();
while (i.hasNext()) {
    ActivityManager.RunningServiceInfo runningServiceInfo = i
            .next();

    if(runningServiceInfo.service.getClassName().equals(serviceName)){
        serviceRunning = true;

        if(runningServiceInfo.foreground)
        {
            //service run in foreground
        }
    }
}
return serviceRunning;

}

如果您想知道服务是否在前台运行,请打开其他一些胖应用程序,然后检查服务是否仍在运行,或者仅检查标志service.foreground

来源:How to determine if an Android Service is running in the foreground?