在Android中绑定到服务的问题

jor*_*bor 4 binding android android-service

我创建了一个名为LocalService的服务,我想绑定它,以便它可以执行某些操作并将结果返回给调用客户端.我一直试图让android dev网站例子工作,但eclipse给出了这个方法的编译时错误:

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;
}
Run Code Online (Sandbox Code Playgroud)

"Binding.this"下面有一条红线,eclipse给我:绑定无法解析为某种类型.我能做什么?

Hit*_*sit 5

只需删除Binding,代码应如下所示:

bindService(new Intent(this, LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
Run Code Online (Sandbox Code Playgroud)

Intent构造函数的第一个参数是Context.如果从Activity类中调用它,则上面的代码将起作用(Activity的任何实例也是Context).如果没有,您始终可以使用应用程序上下文