Problems binding to a service on Android

I created a service called LocalService, and I want to bind to it so that it can perform some action and return the result to the calling client. I am trying to get an example of an Android developer site to work, but eclipse gives a compile-time error for this method:

void doBindService() { // Establish a connection with the service. We use an explicit // class name because we want a specific service implementation that // we know will be running in our own process (and thus won't be // supporting component replacement by other applications). bindService(new Intent(Binding.this, LocalService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBound = true; } 

There is a red line in the "Binding.this" section, and eclipse gives me: binding cannot be allowed for a type. What can I do?

+4
source share
2 answers

Just remove the binding, the code should look like this:

 bindService(new Intent(this, LocalService.class), mConnection, Context.BIND_AUTO_CREATE); 

The first parameter of the Intent Context constructor. The code above will work if you call it from your Activity class (any instance of Activity is also a context). If not, you can always use the application context

+5
source

It looks like Binding is just the name of the class in which you put doBindService() in (most likely activity?). If your class is named differently, rename it to Binding or replace all Binding.this with MyClass.this or just this .

+1
source

Source: https://habr.com/ru/post/1433602/


All Articles