Android Studio - Complete Android Apps Tutorial - Thread and Async Task - Day 13 - 9.34
Thread and AsyncTask
2
Why Another Thread? Failure to return from an Activity callback method within a few seconds 5 secs will cause Android to think your application is stuck Pops an error dialog ANR Kills your activity Even delays shorter than a few seconds will let user feels that the application is unresponsive/slow/lag
3
Handler Only the main thread/UI thread can update the UI, other threads updating the UI will cause CalledFromWrongThreadException If background thread needs to update the UI, request the UI thread to do the update via a Handler Construct a Handler in the main thread Handler mHandler = new Handler;
4
Why Another Thread? Possible reasons: Connecting to Internet to fetch data XML/JSON Since API Level 11, this will cause NetworkOnMainThreadException Reading or writing to a removable storage Many SQLite database operations Lengthy mathematical computations involving many loops
5
Application Not Responding ANR dialog
6
Solved using Thread & Runnable java.lang.Thread java.lang.Runnable Suitable for infinite loop AsyncTask android.os.AsyncTask Suitable for task that will be completed in a finite duration
7
Monitoring Threads Via Android Device Monitor
8
Thread Construct a new Thread Override run in the Thread and the task in run will be run in another thread Start the thread with start new Thread public void run // background task ; .start;
9
Handler Only the main thread/UI thread can update the UI, other threads updating the UI will cause CalledFromWrongThreadException If background thread needs to update the UI, request the UI thread to do the update via a Handler Construct a Handler in the main thread Handler mHandler = new Handler;
10
Handler.post Puts a Runnable on the message queue Will get processed once other messages already on the queue are processed mHandler.postnew Runnable @Override public void run // update UI in main thread ;
11
Handler.postDelayed Like post, except a minimum delay time in milliseconds Will get processed only after the delay time mHandler.postDelayednew Runnable @Override public void run // update UI in main after 1 sec , 1000;
12
Activity.runOnUiThread An alternative to Handler Passed a Runnable If the current thread is a background thread, behaves like post If the current thread is the UI thread, executes Runnable immediately Good for utility code that might be used in different places
13
AsyncTask Bundles thread creation and inter-thread communication in one class Extends and override all runs in UI thread except doInBackground onPreExecute : after the task is executed doInBackgroundParams... : after onPreExecute onProgressUpdateProgress... : after publishProgressProgress... in doInBackground onPostExecuteResult : after completion of doInBackground Create an instance and executeParams...
14
Extends AsyncTask to obtain an inner class AsyncTask is defined by 3 generic types Params, Progress, Result e.g. String, Integer, Boolean, Void, Void, Void Params: the type of the parameters sent to the task upon execution Progress: the type of the progress units published during the background computation Result: the type of the result of the background computation
15
class RefreshTask extends AsyncTaskVoid, Void, Void
@Override protected Void onPreExecute // prepare the UI before the task is run progressBar.setVisibilityView. VISIBLE ;
@Override protected Void doInBackgroundVoid... params // long running process
@Override protected Void onPostExecuteVoid result // update the UI after task is done progressBar.setVisibilityView. INVISIBLE ;
Using AsyncTask
16
class RefreshTask extends AsyncTaskString, Void, Boolean
@Override protected Boolean doInBackgroundString... params String url = params0; // get the 1st parameter // long running process return true;
@Override protected Void onPostExecuteBoolean result ifresult // handle successful task
Using AsyncTask with parameters
17
class RefreshTask extends AsyncTaskVoid, Integer, Void
@Override protected Void doInBackgroundVoid... params // long running process publishProgresscount; // long running process
@Override protected Void onProgressUpdateInteger... values int progress = values0; // update the progress bar
Using AsyncTask – publish progress
18
Running AsyncTask new RefreshTask.execute; Running AsyncTask with parameters new RefreshTask.execute“http://www.android.com”; new RefreshTask.execute1, 2, 3; Running multiple AsyncTask in parallel Default behaviour for API Level lower than 11 For API Level 11 or higher new RefreshTask.executeOnExecutorAsyncTask. THREAD_POOL_EXECUTOR;
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Android Studio - Complete Android Apps Tutorial - Thread and Async Task - Day 13 - 9.34», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.