问题
I just started working on an application for Android, to be specific - a service.
I would like to create a service (background service, forcing itself to run, hidden, so it can't be shut down). and I don't have idea on how to construct it. How it is then launched and how to make it fit to those requirements. It needs to start running from the Android start, so I guess it would be created similarly to system services (or as a system service).
You may ask why I need that - I would like it to periodically send some data to MySQL DB without any user interaction - therefore it needs to run continuously.
It would be really helpful if You could give me a great start, a tutorial maybe or some structure drawing with crucial information.
One more thing - I am targetting Android 2.3, but if it's impossible, I'd like it to be the lowest possible Android version.
Thanks in advance guys!
回答1:
I would like to create a service (background service, forcing itself to run, hidden, so it can't be shut down).
Fortunately, this is not possible. Users have control over their device, not you, and they can shut down whatever they want.
It needs to start running from the Android start, so I guess it would be created similarly to system services (or as a system service).
System services are part of the operating system and cannot be created via the Android SDK.
You may ask why I need that - I would like it to periodically send some data to MySQL DB without any user interaction - therefore it needs to run continuously.
It does not need "to run continuously". That would be a singularly poor implementation.
If you want to do something periodically, use AlarmManager
for the scheduling. The work should be done by an IntentService
, so the service can go away when the work is done, so you are not tying up memory all of the time and making it more likely that the user will shut you down. If you plan on waking up the device out of sleep mode to do the work, you should look into WakefulBroadcastReceiver
, or possibly my WakefulIntentService.
回答2:
Alright, I found the answer myself, but thanks for help to any of You who contributed :)
I am aware that it's not the best approach, but I need to do it that way, so I found this for running a service and restart after stopped, also found that for start the service/application on boot.
Both tested and worked for me.
I hope it is going to help anyone who needs it.
回答3:
Do you want this service to be executed daily?? You need alarm manager .. that will help you in to start you service with android start and will execute your service after specified time delay.. You can specify the time for delay also. Dont forget to add permissions for alarm manager in manifest file.
来源:https://stackoverflow.com/questions/18917380/android-stand-alone-service