简体   繁体   中英

Android - How can Services run in background?

To my understanding, on android, Services run on the UI thread. I'm a little confused as to how services can run in the background - Should that not block the UI thread? How come they can both be on the main thread and run in the background at the same time?

Services run on the main thread by default, but they run in the background from the user's perspective - there's no screen backing the Service .

If you want your service to execute on a background thread, either use a Service subclass and provide your own threading - via a new Thread , the Java Executor framework, RxJava , AsyncTask , or use an IntentService subclass for "one-shot" type of tasks.

You can easily organize execution in background by yourself. But, if you want to perform single continious job once, consider using IntentService - it will run in separate thread and then finish. On the other hand, ordinary Service ca run indefinitely and you can bind to it. There is a few ways you can organize background tasks - AsyncTask, separate Thread, and, the most powerfull and convenient way- use rxJava library

Here is a code how you can execute some operation in background thread and process results on main thread with rxJava:

String arg = "132";
        Observable.defer(() -> Observable.just(arg))
                // start operation on background thread from
                // thread pool
                .subscribeOn(Schedulers.computation())
                .map(arg -> {
                    // do you processing here
                    String result = "123";
                    return result;
                })
                // switch to main thread
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(v -> {
                    // process results
                    Log.i("My service", "result: " + v);
                }, error -> {
                    // handle error
                });

As you can see, this is very convenient way of managing background operation, but, more importaint, you can switch threads as task progresses.

Service is always run on UI Thread

But If you run a service in UI thread then UI will be blocked.

So within the help of Thread or Asynctask you can call a service via Sap-rate Thread so that UI will not be blocked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM