5

我注意到这Service.START_STICKY不起作用,当我仔细观察时,我看到 onCreate() 正在运行,但没有调用 onStartCommand。

任何想法为什么?

    @Override
public void onCreate() {

    mGlobalData = GlobalData.getInstance();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    if (mTimer == null)
        mTimer = new Timer();

    Log.e(TAG, "onCreate()");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    int t = START_STICKY;
    Log.e(TAG, "call me redundant BABY!  onStartCommand service");

    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return t;
}
4

2 回答 2

15

如果您遇到与我相同的情况,我的Service启动和运行都很好(onCreate()并且onServiceConnected()都被调用)但从onStartCommand(Intent,int)未被调用。我发现这是因为系统启动了我Service而不是我明确地启动了Servicein 代码。根据文档

[onStartCommand(Intent,int)是] 每次客户端通过调用显式启动服务时由系统调用startService(Intent)

所以我必须startService(new Intent(context, MyService.class))在代码中显式调用onStartCommand(Intent,int)才能触发。请注意,这样做不会重新启动系统创建的服务,也不会创建该服务的新实例。

于 2015-12-04T16:17:10.740 回答
2

尝试android.os.Debug.waitForDebugger();onCreate(). 在我这样做之前,调试器没有达到onStartCommand()我的断点。

于 2013-04-23T13:04:27.867 回答