【发布时间】:2012-01-25 16:59:13
【问题描述】:
我在将服务绑定到 Android 中的活动时遇到问题。问题出现在activity中:
public class ServiceTestActivity extends Activity {
private static final String TAG = "ServiceTestAct";
boolean isBound = false;
TestService mService;
public void onStopButtonClick(View v) {
if (isBound) {
mService.stopPlaying();
}
}
public void onPlayButtonClick(View v) throws IllegalArgumentException, IllegalStateException, IOException, InterruptedException {
if (isBound) {
Log.d(TAG, "onButtonClick");
mService.playPause();
} else {
Log.d(TAG, "unbound else");
Intent intent = new Intent(this, TestService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
isBound = true;
}
};
}
isBound 告诉服务(称为 TestService)是否已经绑定到活动。 mService 是对服务的引用。
现在,如果我第一次调用“onPlayButton(..)”,而服务未绑定,则调用 bindService(..) 并且 isBound 从 false 切换为 true。然后,如果我再次调用“onPlayButton(..)”,它会在服务对象上调用“playPause()”。到这里一切正常。
但我希望在服务绑定后立即调用“playPause()”,所以我将代码更改为:
public void onPlayButtonClick(View v) throws IllegalArgumentException, IllegalStateException, IOException, InterruptedException {
if (isBound) {
Log.d(TAG, "onButtonClick");
mService.playPause();
} else {
Log.d(TAG, "unbound else");
Intent intent = new Intent(this, TestService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
mService.playPause();
}
}
从现在开始我得到一个 NullPointerException,因为 mService 没有对绑定服务的引用,它仍然是 null。我通过在代码的不同位置记录 mService 的值来检查这一点。
关于我在这里做错了什么的任何提示?我对在 android 中编程(尤其是绑定)服务非常陌生,但我仍然看不出我的 to 版本之间的主要区别在哪里。
【问题讨论】:
标签: android android-service android-activity