Android: 无法绑定到已经 运行 的服务,未调用 onServiceConnected

Android: cannot bind to already running service, onServiceConnected not called

我有 运行 服务(之前 成功 绑定、启动并与主 activity 解除绑定):

Intent startingIntent = new Intent(this, SturkoPlayerService.class);
startingIntent.setAction(SturkoPlayerService.PLAYER_START);
bindService(startingIntent, connection, Context.BIND_AUTO_CREATE);

当我成功关闭 mainactivity(服务未绑定并保持 运行)并想重新打开 mainactivity 并通知意图时:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("Service", 1);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); //tried also another flags
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

然后尝试绑定我的 运行 服务

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ...

    if (getIntent() != null && getIntent().hasExtra("Service")) {
        if (!bound) {
            bindService(new Intent(this, SturkoPlayerService.class), connection, 0);
        }
    }
}

我的 Connection 变量的 onServiceConnected 函数未被调用

private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        SturkoPlayerService.LocalBinder mBinder = (SturkoPlayerService.LocalBinder) service;
        sturkoService = mBinder.getService();
        bound = true;
        sturkoService.registerClient(MainActivity.this);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        bound = false;
    }
};

清单:

...
<activity android:name=".MainActivity"
    android:screenOrientation="portrait"
    android:launchMode="singleTask"> //tried other modes too
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<service
    android:name=".Service.SturkoPlayerService"
    android:enabled="true"
    android:exported="true"
    android:singleUser="true">
</service>
...

P.S.: 目录没有显示东西

只有在以下情况下,服务才会 运行:

  • 绑定了1+个客户端,或者

  • 您在其上调用了 startService(),但没有任何阻止(例如,stopSelf()stopService()

否则,一旦最后绑定的连接解除绑定,服务将停止。