There is a Service and Activity , a connection between them is established via IBinder. Activity implements a certain interface, say onLoadCompleteListener . Service calls the onLoadCompleteListener.onLoadComplete method when an operation is completed.

Activity:

 @Override public void onLoadComplete() { final TextView textView = (TextView) findViewById(R.id.textView); textView.setText("text"); // будет вызван Ecxeption "Only original thread that created a view..." } 

Service:

 public onLoadCompleteListener listener; public void onStartCommand(...) { listener.onLoadComplete(); } class SBinder extends Binder { Service getService(MyInterface ilistener) { listener = ilistener; return Service.this; } } 

Examples do not bring any practical benefits, and are needed only to explain the question.

When you call onLoadComplete() application crashes with the error "You can view its views". The question arises: is the service really running not in the same thread as the Activity as indicated in the manuals?

  • one
    If I’m not mistaken, the ServiceConnection should be used to connect to the service, which asynchronously, does not connect to the service in the UI stream, and so, see, further interaction is not carried out in the main stream - Yurii
  • Your mistake means only that you listener.onLoadComplete(); cause in some other thread. The question has nothing to do with the service, you can achieve the same effect in the activity (in asynctask, for example, by referring to ui in doInBackground). If you start another thread in some method and call the callback from it, then it will be executed in the same other thread, no magic will be automatically returned to the main thread. - Yura Ivanov

1 answer 1

Service in android works in the main thread. To run in the background thread, you need to use either AsyncTask or Thread . Or use IntentService . This is a subclass of the usual Service . It has an onHandleIntent method onHandleIntent runs in the background thread.