Android 教程 使用Service
2010-05-06 16:23:00 来源:WEB开发网_boundService = null;
Toast.makeText(TestServiceHolder.this, “Service connected”,
Toast.LENGTH_SHORT).show();
}
};
private void initButtons() {
Button buttonStart = (Button) findViewById(R.id.start_service);
buttonStart.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startService();
}
});
Button buttonStop = (Button) findViewById(R.id.stop_service);
buttonStop.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
stopService();
}
});
Button buttonBind = (Button) findViewById(R.id.bind_service);
buttonBind.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
bindService();
}
});
Button buttonUnbind = (Button) findViewById(R.id.unbind_service);
buttonUnbind.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
unbindService();
}
});
}
private void startService() {
Intent i = new Intent(this, TestService.class);
this.startService(i);
}
private void stopService() {
Intent i = new Intent(this, TestService.class);
this.stopService(i);
}
private void bindService() {
Intent i = new Intent(this, TestService.class);
bindService(i, _connection, Context.BIND_AUTO_CREATE);
_isBound = true;
}
private void unbindService() {
if (_isBound) {
unbindService(_connection);
_isBound = false;
}
}
}
这里可以看到两种启动方法,start和bind,当然也是通过intent调用的,在intent中指明指定要启动的Service的名字,stop也一样
更多精彩
赞助商链接