1

我正在尝试让服务在 Android 中运行。我的应用程序现在可以启动我的服务,但是当服务在后台运行并且我启动我的(主)活动时,服务将重新启动(将调用onCreate()和命令)。onStartCommand()在我的 MainActivity 中,我通过以下代码检查服务是否已在运行:

    if (isServiceRunning()){
        System.out.println("De serice is running");
    }
    else{
        System.out.println("De service is niet running");
        startService(new Intent(this, YourService.class));
    }
...
private boolean isServiceRunning() {
    ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        Log.d("services", service.service.getClassName());
        if ("com.vandervoorden.mijncijfers.YourService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

当我的服务正在运行时,我的控制台中会显示“De serice 正在运行”。

为什么在我自己没有重新启动服务时调用onCreate()and ?onStartCommand()如何确保服务在已经启动时不会启动两次?

编辑 1 2013-10-07 下午 8:54:

我的服务等级:

public class YourService extends Service
{
    Alarm alarm = new Alarm();

    public void onCreate()
    {
        super.onCreate();
        System.out.println("service: onCreate");
    }


    public int onStartCommand(Intent intent, int flags, int startId) {
        //alarm.SetAlarm(this);
        System.out.println("service: onStartCommand");
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
}
4

1 回答 1

2

This behavior looks weird only if you are sure you are not destroying your service somewhere in the activity, even so what I usually do to make sure that only one instance of my service is running, is flagging the service itself using a static flag that keeps track of "onCreate" and "onDestroy", this way independently if the activity would like to start my service I have the validations in the service itself.

Hope this Helps.

Regards!

于 2013-10-07T18:51:54.567 回答