How to Start a Background Thread in Android

When we try to execute long running operations on the app’s main thread (also called the UI thread), we freeze the app’s user interface and after a couple seconds we get an “application not responding” dialog message with the option to force quit the app. To avoid this we have to move heavy operations like database manipulation and network requests onto a separate thread.
In this video we will learn how to create such a separate worker thread in Android. For this we can either create a class that extends Thread and override it’s run method, or create a class that implements the Runnable interface, and then pass this Runnable to a new Thread object.
These core Java classes build the foundation for classes like AsyncTask, HandlerThread and ThreadPoolExecutor.
We will also learn how to send code from the background thread back to the UI thread by calling post on a Handler that sends a runnable to the MessageQueue of the UI thread. To associate the Handler with the Looper of the main thread, we either instantiate it on the main thread, or pass Looper.getMainLooper to the constructor.
Instead of creating a handler, we can also use the View classes post method or the Activity classes runOnUiThread method, that use the main handler internally.

Great explainer video by the Android developer team about threads, handlers, loopers etc:
https://www.youtube.com/watch?v=0Z5MZ0jL2BM

Example code:
https://codinginflow.com/tutorials/android/starting-a-background-thread

____________________
Subscribe to my channel:
https://www.youtube.com/c/codinginflow?sub_confirmation=1

Want more Android tutorials? Check my playlist section:
https://www.youtube.com/c/codinginflow/playlists

Follow me on social media:

Facebook:
https://www.facebook.com/codinginflow

Instagram:
https://www.instagram.com/codinginflow

Twitter:
https://twitter.com/codinginflow

Blog:
https://codinginflow.com/

AsyncTask + WeakReference – Android Studio Tutorial

In this video we will learn, how to use the AsyncTask class, which makes it easier to do operations on a background thread and publish the results on the UI/main thread, without having to manipulate threads and handlers ourselves.
For this we will subclass Asynctask, define 3 generic types for the params, the progress and the result and override 4 methods:
onPreExecute, where we do preparations on the UI thread, doInBackground where we do the heavy work on a background thread, onProgressUpdate where we publish the progress to the UI thread (for example to a ProgressBar), and onPostExecute where we get back the result from the background task.
In order to not leak memory by holding onto a strong reference to our MainActivity, we will make the AsyncTask static and keep a WeakReference to our Activity.

Example code:
https://codinginflow.com/tutorials/android/asynctask

____________________
Subscribe to my channel:
https://www.youtube.com/c/codinginflow?sub_confirmation=1

Want more Android tutorials? Check my playlist section:
https://www.youtube.com/c/codinginflow/playlists

Follow me on social media:

Facebook:
https://www.facebook.com/codinginflow

Instagram:
https://www.instagram.com/codinginflow

Twitter:
https://twitter.com/codinginflow

Blog:
https://codinginflow.com/

Channel: Coding in Flow
Published: 2018-03-11 23:30:45
Duration: 16M23S
Views: 9070
Likes: 317
Favorites: 0

JobScheduler – Android Studio Tutorial

Since Android Oreo, idle apps can’t keep background services running anymore. So if you need to do operations even if your app is not running in the foreground, you should use a JobScheduler instead.
In this video we will set up such a JobScheduler by creating a class that extends JobService and then scheduling it with the JOB_SCHEDULER_SERVICE.
In the JobService class, we override onStartJob and onStopJob. In onStartJob we will start a background thread to do some long running (fake) operations. In onStopJob we cancel our work because the system will release the wakelock when the criteria for our job are not met anymore (for example we required an unmetered network and the user disables WiFi). In this case we will reschedule our task to try again later.
When we schedule our job, we pass a JobInfo object to the JobScheduler, which will define under which circumstances we want the system to execute our job. Here we can set criteria like setRequiresDeviceCharging, setRequiredNetworkType, setPeriodic and more. We can even make it survive device reboots with setPersisted.
Lastly we register our JobService in the manifest with the android.permission.BIND_JOB_SERVICE permission and the system will then start our service at the appropriate time, even if our app is not running.

Example code:
https://codinginflow.com/tutorials/android/jobscheduler

JobInfo.Builder documentation:
https://developer.android.com/reference/android/app/job/JobInfo.Builder.html

____________________
Subscribe to my channel:
https://www.youtube.com/c/codinginflow?sub_confirmation=1

Want more Android tutorials? Check my playlist section:
https://www.youtube.com/c/codinginflow/playlists

Follow me on social media:

Facebook:
https://www.facebook.com/codinginflow

Instagram:
https://www.instagram.com/codinginflow

Twitter:
https://twitter.com/codinginflow

Blog:
https://codinginflow.com/

Channel: Coding in Flow
Published: 2018-03-26 17:55:06
Duration: 16M14S
Views: 35049
Likes: 714
Favorites: 0

IntentService on Android Oreo

In this video, we will learn how to start and use IntentServices in Android.
An IntentService runs in the background independently from an activity and handles all the incoming work on a HandlerThread, so we don’t have to take care of creating our own background thread in order to not block the UI thread.
Since IntentService is a subclass of Service and therefore affected by the Android Oreo background execution limits, the recommended approach is to use the JobIntentService instead, which uses JobScheduler to enqueue a job on API 26 and higher.
In this video we will use a different approach and run our IntentService as a foreground service on Android Oreo and higher, but as a normal background service on API 25 and lower.
For this, we create a class that extends IntentService, where we provide a default constructor and override onCreate, onHandleIntent and onDestroy. We don’t have to implement onBind, since the superclass provides a default implementation that returns null. When the Service is created, onCreate is triggered. Here, we display a persistent notification (after creating a notification channel in the Application class) and call startForeground if the SDK_INT is VERSION_CODES.O or higher to promote the service to a foreground service. In onHandleIntent, all the incoming intents are executed on a worker thread sequentially, one after another. When an intent is processed, the next one is started automatically. Here we can do long-running work synchronously without blocking the main thread. We can send data to the service in form of intent extras and when the last intent is finished, the service stops itself and onDestroy is triggered. This means that we don’t have to call stopSelf or stopService.
In order to keep the CPU running even after the screen is turned off, we can acquire a partial wake lock in onCreate with help of the PowerManager’s newWakeLock method. In onDestroy we release this wake lock. Optionally, we can pass a long value for the timeout in milliseconds, which takes care of releasing the wake lock in case anything went wrong and release is not called. This avoids that our wake lock drains the user’s battery.
With setIntentRedelivery, we can define what should happen if the system kills the service (for example in low memory situations). A boolean value of false is the equivalent of returning START_NON_STICKY from onStartCommand in a normal service, and true equals START_REDELIVER_INTENT.
Lastly, we have to request the WAKE_LOCK and FOREGROUND_SERVICE (Android Pie) permissions in the Manifest, register our service and Application class there and call startService or ContextCompat.startForegroundService in our MainActivity to start the service.

Watch the foreground service tutorial first:
https://www.youtube.com/watch?v=FbpD5RZtbCc

Example code:
https://codinginflow.com/tutorials/android/intentservice

____________________
Subscribe to my channel:
https://www.youtube.com/c/codinginflow?sub_confirmation=1

Want more Android tutorials? Check my playlist section:
https://www.youtube.com/c/codinginflow/playlists

Follow me on social media:

Facebook:
https://www.facebook.com/codinginflow

Instagram:
https://www.instagram.com/codinginflow

Twitter:
https://twitter.com/codinginflow

Blog:
https://codinginflow.com/

Channel: Coding in Flow
Published: 2018-11-17 11:46:37
Duration: 19M24S
Views: 6388
Likes: 136
Favorites: 0

How to Start a Foreground Service in Android (With Notification Channels)

In this video we will learn how to start a foreground service in Android, which runs independently from other app components (like activities), but displays a persistent notification to the user as long as it is running.
We create our foreground service by extending the Service class and overriding onStartCommand, where we then promote our service to the foreground by calling startForeground and passing a notification to it, which we build with the NotificationCompat.Builder.
With target API level 26 (Android Oreo) or higher, we have to create notification channels in order to be able to display notifications, and we will do this is in the Application class.
Depending if we want to restart the service if the system kills it, we return either START_STICKY, START_NOT_STICKY or START_REDELIVER_INTENT from onStartCommand.
Additional we can override onCreate and onDestroy, where we can do an initial setup and a cleanup. We also have to override onBind, but since we are creating a started service and not a bound service, we can just ignore this method and return null.
We register our service in the AndroidManifest.xml file and then we can start it by calling startService, startForegroundService or ContextCompat.startForegroundService, where we have to pass an intent, which can optionally contain data in form of extras.
We stop the service by calling either stopSelf from within, or stopService from another app component.

Example code:
https://codinginflow.com/tutorials/android/foreground-service

____________________
Subscribe to my channel:
https://www.youtube.com/c/codinginflow?sub_confirmation=1

Want more Android tutorials? Check my playlist section:
https://www.youtube.com/c/codinginflow/playlists

Follow me on social media:

Facebook:
https://www.facebook.com/codinginflow

Instagram:
https://www.instagram.com/codinginflow

Twitter:
https://twitter.com/codinginflow

Blog:
https://codinginflow.com/

Channel: Coding in Flow
Published: 2018-05-11 07:26:27
Duration: 23M23S
Views: 39919
Likes: 752
Favorites: 0

Leave a Reply

Your email address will not be published. Required fields are marked *