可以通过调用它的方法与服务进行通信吗?

时间:2013-09-05 13:30:14

标签: java android android-activity android-service

如前所述here和所有开发人员一样,Activity有几种方式可以与Service进行通信。最流行的方法是使用Intent数据和绑定。是否可以通过调用它的方法与服务进行通信? 如果有可能,这是一个好方法吗?

1 个答案:

答案 0 :(得分:1)

是的,您只需要从活页夹返回服务实例。请查看at this article以获取有关如何执行此操作的示例。

从上面链接的文章中提取(查找行:int num = mService.getRandomNumber();)。

LocalService.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;
    }

    public int getRandomNumber() {
      return 5;
    }
}

BindingActivity.java

public class BindingActivity extends Activity {
    LocalService mService;
    boolean mBound = false;

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;

            // Call the method from service
            int num = mService.getRandomNumber();
        }
    };
}