Service not registered solution

My question is as follows, readers will see if it is the same as mine.
Problem description:
When creating the foreground service, a notification Notification is established. When
bindService(intent, connection, BIND_AUTO_CREATE); is used in the activity , we start the foreground service, and the simulator can also see the creation of the notification, and then I click Notice.
Because the notification is set with setContentIntent(Pi),
Intent intent = new Intent(this, Activity.class);
PendIntent pi = PendIntent.getActivity(this,0,intent,0);
so after clicking the notification, it will jump to the activity Activity.
Then, when you unbindService(connection) again, the system crashes and the LogCat log shows Service not registered

Cause Analysis:

Service not registered is because bindService() is not called, but unbindService() is called
. UnbindService does not find the connection object and cannot find the started service, so an error is reported.

doubt:

Why can't I find the Service when I clicked bindService()?

Conclusion: The
problem is
because the notification is set to setContentIntent(Pi),
Intent intent = new Intent(this, Activity.class);
PendIntent pi = PendIntent.getActivity(this,0,intent,0);
so it will jump after clicking the notification Go to the activity Activty, and the LauchMode of the activity is Standard by default, so a new activity will be recreated, and the connection object in the previous activity will naturally not be available.
solution

  1. Isn't it easy to retrieve the connection object? Press the return button to return to the previous activity. At this time, call unbindService() to close the service, and no error will be reported.
  2. Or set the launch mode of this activity LauchMode to the stack top multiplexing mode
    SingleTop; then clicking the notification will not start a new activity

The nonsense is behind
. What did the author say so much useless nonsense? nonsense? This is not to explain to you the conditions, reasons, and solutions of this problem.

Guess you like

Origin blog.csdn.net/qq_41904106/article/details/115105671