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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

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

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    /** Called when a button is clicked (the button in the layout file attaches to
      * this method with the android:onClick attribute) */
    public void onButtonClick(View v) {
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            int num = mService.getRandomNumber();
            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
        }
    }

    /** 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;
        }

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

这是http://developer.android.com/guide/components/bound-services.html中的一个示例。我想直接使用mService,不需要先点击按钮,怎么办。我尝试了很多方法,但它们都行不通。

4

1 回答 1

0

我怀疑您遇到的问题是绑定到服务是异步的。因此,您需要等到恢复服务后才能拨打电话。如果您调用 bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 从 onCreate 说起,您可能在活动启动生命周期的任何时候都不会拥有该服务...... mService 仍然为空。如果您不想让用户等待您执行此操作(通过花费几秒钟点击按钮),您可以简单地从您的 onServiceConnected 方法调用 mService,它应该可以正常工作。无论哪种方式,关键是等待对 mService 进行任何调用,直到 onServiceConnected 已运行且 mService 不再为空。(这可能会onResume 之后发生)。那有意义吗?

于 2013-05-03T14:15:25.360 回答