gpt4 book ai didi

Android 服务 onStartCommand 从未调用过

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:41 26 4
gpt4 key购买 nike

我注意到 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;
}

最佳答案

如果您遇到与我相同的情况,我的 Service 启动并运行得很好(onCreate()onServiceConnected() 是都被调用了)但是 onStartCommand(Intent,int) 从未被调用过。我发现是因为系统启动了我的Service,而不是我在代码中显式启动了Service。根据docs :

[onStartCommand(Intent,int) is] called by the system every time a client explicitly starts the service by calling startService(Intent)

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

关于Android 服务 onStartCommand 从未调用过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12928767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com