在同一个方法中使用绑定服务时,由于异步加载的原因,服务可能未完成绑定即被调用,从而导致失败。为解决该问题,可以通过使用回调方法或使用Handler来处理异步加载。
示例代码:
public class MainActivity extends AppCompatActivity {
private MyService mService;
private boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
MyService.MyBinder binder = (MyService.MyBinder) iBinder;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 绑定服务
Intent intent = new Intent(this, MyService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
// 此处使用 Handler 处理异步加载
new Handler().post(new Runnable() {
@Override
public void run() {
// 使用绑定服务
if (mBound) {
mService.doSomething();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
}
上一篇:绑定非静态函数到回调函数的问题