如何重新绑定到前台服务?

时间:2017-10-22 09:29:28

标签: android android-activity android-service android-service-binding

启动前台服务并立即绑定到该服务。有没有办法知道服务已经停止或活动重启后是否仍在运行。安全的方法是执行digraph incl { define(`edge_x',`[label="type x", color=red, style=solid]') define(`edge_y',`[label="type y", color=green, style=dashed]') define(`edge_z',`[label="type z", color=blue, style=dotted]') include(gv1.txt) include(gv2.txt) e -> d[ color = yellow, label = "this is new!"]; } ,但是有更清洁的吗?

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法:

https://stackoverflow.com/a/6452570/5457878

检查您的服务是否仍在运行。您可以在onResume()onCreate()中调用此方法,如果它未运行,我会重新启动它。

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;
}