0

I would like to send the broadcast message back to the activity when the service is stopped by the user or OS. I have tried to add the code in onDestroy of the service while onDestroy have not been called every time.

Can anyone give me suggestion how I can send the message when the service is stopped?

shisushi
  • 215
  • 1
  • 2
  • 8

1 Answers1

0

Try using StartSticky and sending a broadcast every time the service start(onStart). So when it is destroyed, the service will try to run again by itself and will send the broadcast. This way you will know when the server have been closed and open again.

P.D: Remember to send the broadcast in the onStart, not in onCreate.(Service Lifecycle.)

SamuelPS
  • 555
  • 6
  • 20
  • Thanks for your answer. Do you mean sending a broadcast that the service is stopped in onStartCommand? But I also need to send a broadcast to tell the activity that the service is started. – shisushi Sep 15 '16 at 14:26
  • No. Just send one broadcast when the service start. If you start the service Sticky, it will be launched againwhen the user or the S.O kill it. So everytime you receive the broadcast it means that the service have been closed and relaunched. – SamuelPS Sep 15 '16 at 14:28
  • Could you give more info? What is the purpose of that service? Why do you want to know if the service stopped? – SamuelPS Sep 15 '16 at 14:32
  • Actually, I don't need to service the launch again automatically. I just want the restarted activity to know the service (run in foreground) had stopped before the user starts the service again manually. – shisushi Sep 15 '16 at 14:34
  • Sorry for unclear question. The service is to check if the specific wifi is connected and forward the call to a number if connected. I want the service to send 3 different content of broadcast, started but not forward, start and forwarded to a number, stop and show it in the textview in the activiy – shisushi Sep 15 '16 at 14:36
  • Since the service is run on foreground while the activity may be stopped. the status of the service is not shown correctly when the service is stopped by user as it does not send the broadcast to the activity – shisushi Sep 15 '16 at 14:39
  • I have searched the information of startsticky. It said the service will get null intent. But the service needs to get extras in the intent to do processes. Or mayby I should use START_REDELIVER_INTENT? – shisushi Sep 15 '16 at 14:47