How to start long running background task in android service

后端 未结 2 1083
醉话见心
醉话见心 2021-01-05 08:25

Having read most of the available documentation on Android services on the developer site and here in stackoverflow, I\'m still confused by several aspects of running a serv

相关标签:
2条回答
  • 2021-01-05 09:07

    I think you could use a IntentService which you run by setting up a (regular) alarm (AlarmManager.setRepeating) with a PendingIntent in it. You can notify the UI by broadcasting an Intent from the IntentService and receiving it in your UI through a BroadcastReceiver.

    0 讨论(0)
  • 2021-01-05 09:26

    so that the service run in its own thread.

    That puts the service in its own process. This is generally something to be avoided, as it consumes extra RAM and CPU (for IPC). You can create a thread just by creating a Thread or any number of other means, most of which have been in Java for a decade or so.

    At the risk of ignoring battery issues etc, basically I'd like it to run forever.

    It is pretty much impossible for a service to run forever. Users or the OS will get rid of your service eventually.

    What is the best way to initiate this method/task ?

    Call dummytask() from a background thread.

    do I need to use AIDL instead?

    No. Your service can broadcast an Intent, or invoke a PendingIntent supplied by the activity, or send a Message via a Messenger supplied by the activity, etc. The best would be to use the LocalBroadcastManager from the Android Support package, but that will not work across process boundaries, forcing you into more expensive communications options.

    0 讨论(0)
提交回复
热议问题