0

正如这里提到的和所有开发人员所做的那样,有几种方法可以让 anActivityService. 最流行的方法是使用 Intent 数据和绑定。是否可以简单地通过调用它的方法与服务进行通信?如果可能的话,这是一个好方法吗?

4

1 回答 1

1

是的,您只需从活页夹中返回服务实例。查看这篇文章,了解如何执行此操作的示例。

摘自上面链接的文章(查找行:)int num = mService.getRandomNumber();

本地服务.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();
        }
    };
}
于 2013-09-05T13:37:44.837 回答