访问绑定服务中的外部类实例

时间:2016-05-08 14:57:24

标签: java android service

在android绑定服务中,以下片段使用Foo.this访问服务实例,但实际上如果我们尝试在java中执行它,则无法实现。它是如何工作的?

public class LocalService extends Service { 
  private final IBinder mBinder = new LocalBinder();

  public class LocalBinder extends Binder {
    LocalService getService() {
        return LocalService.this;
    }
  }

  @Override public IBinder onBind(Intent intent) { return mBinder; }

  // Other public methods below
  public void foo() {} // etc...
}

// The activity class
public class MyActivity extends Activity {
  LocalService mService;
  boolean mBound = false;
  ....
  .....
  private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service)   {

        LocalBinder binder = (LocalService.LocalBinder) service;
        /* See, using this we can get the instance of LocalService in android, but using the same approach in java we get the error. */
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
  };
}

正如您在MyActivity类中看到的,我们可以使用LocalService方法获取getService()类的实例(之后我们可以访问它的方法)。但是如果我们尝试在java中这样做,我们就会得到错误。

简而言之,binder.getService()调用如何在android中运行。

0 个答案:

没有答案