Created
January 24, 2019 17:01
-
-
Save rinekri/5a14f2ee6e7c29e32d9ef94de64a2a43 to your computer and use it in GitHub Desktop.
Intent service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class TimerHandlerService : IntentService(TAG) { | |
| companion object { | |
| private const val TAG = "TimerHandlerService" | |
| private const val EXTRA_WITH_LOOP = "$TAG.with_loop" | |
| fun newIntent(context: Context, withLoop: Boolean): Intent { | |
| return Intent(context, TimerHandlerService::class.java).apply { | |
| putExtra(EXTRA_WITH_LOOP, withLoop) | |
| } | |
| } | |
| } | |
| private var uiHandler: Handler? = null | |
| private var shouldReleaseResources = false | |
| override fun onCreate() { | |
| super.onCreate() | |
| shouldReleaseResources = false | |
| Log.e(TAG, "onCreate") | |
| uiHandler = Handler() | |
| "$TAG: onCreate".showToast(applicationContext) | |
| } | |
| // NOTE: Нужно очищать ресурсы: потоки, ресурсы и т.д. | |
| // Иначе будут утечки - например, бесконечный цикл будет выполняться дальше. | |
| override fun onDestroy() { | |
| super.onDestroy() | |
| shouldReleaseResources = true | |
| Log.e(TAG, "onDestroy") | |
| "$TAG: onDestroy".showToast(applicationContext) | |
| } | |
| override fun onHandleIntent(intent: Intent) { | |
| Log.e(TAG, "onHandleIntent") | |
| if (intent.extras.getBoolean(EXTRA_WITH_LOOP)) { | |
| var second = 0 | |
| while (!shouldReleaseResources) { | |
| if (second == 0) { | |
| "$TAG: invoked" | |
| } else { | |
| "$TAG: $second seconds elapsed" | |
| }.also { | |
| Thread.sleep(2000L) | |
| uiHandler?.post { it.showToast(applicationContext) } | |
| Log.e(TAG, it) | |
| } | |
| second += 2 | |
| } | |
| } else { | |
| uiHandler?.post { "onHandleIntent".showToast(applicationContext) } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment