Android服务onStartCommand从未调用过

Asa*_*ssi 5 android android-service

我注意到它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;
}
Run Code Online (Sandbox Code Playgroud)

kpn*_*a12 13

如果你有同样的情况,我Service启动并运行得很好(onCreate()并且onServiceConnected()都被调用)但从onStartCommand(Intent,int)未被调用过.我发现这是因为系统启动了我,Service而不是我明确启动Servicein代码.根据文件:

[ onStartCommand(Intent,int)是]由系统每一个客户明确通过调用启动服务时被调用startService(Intent)

所以我必须startService(new Intent(context, MyService.class))在代码中明确调用onStartCommand(Intent,int)才能触发.请注意,执行此操作不会重新启动系统创建的服务,也不会创建该服务的新实例.


小智 2

android.os.Debug.waitForDebugger();尝试在 的末尾插入该行onCreate()。在我执行此操作之前,调试器没有到达onStartCommand()我的断点。