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,不需要先点击按钮,我该怎么办。我尝试了很多方法,但它们都行不通。
答案 0 :(得分:0)
我怀疑你遇到的问题是绑定到服务是异步的。因此,您需要等到恢复服务后才可以打电话给它。如果调用bindService(intent,mConnection,Context.BIND_AUTO_CREATE);从onCreate开始,你可能在活动启动生命周期中的任何时候都没有服务...... mService仍然是null。如果您不想让用户这样做等待您(通过花几秒钟点击按钮),您只需从onServiceConnected方法调用mService即可,它应该可以正常工作。无论哪种方式,关键是等待对mService进行任何调用,直到运行onServiceConnected并且mService不再为null。 (这可能会发生在甚至onResume之后)。这有意义吗?