Android之Service应用实例
2010-06-12 20:13:00 来源:WEB开发网public class MyActivity extends Activity {
private MyService mService;
private static boolean ISRUNNING = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startMyService();// 启动
}
@Override
public void onResume() {
super.onRestart();
if (ISRUNNING) {
bindMyService();
}
}
@Override
public void onDestroy() {
super.onDestroy();
// if (ISRUNNING) {
// unbindMyService();
// }
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mService =
((MyService.MyBinder)service).getServices();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
Intent intent = new Intent(MyActivity.this, MyService.class);
// 启动服务
private void startMyService() {
startService(intent);
ISRUNNING = true;
}
// 绑定
private void bindMyService() {
bindService(intent, mConnection,Context.BIND_AUTO_CREATE);
}
// 取消绑定
private void unbindMyService() {
unbindService(mConnection);
}
private void stopMyService() {
stopService(intent);
ISRUNNING = false;
}
}
上述代码展示了一个Activity(Client)如何启动并绑定一个服务的。主要是利用了Activity的生命周期来创建、绑定、取消绑定一个服务。
上面代码中没有没用调用stopMyService()退出个服务,可根据你的需要进行调用。
更多精彩
赞助商链接