- Start服务开启方式
1) 创建服务
public class MyService extends Service
2) 添加注册表
<service android:name="cn.itang.fuwudemo.MyService"></service>
3) 重写方法
public void onCreate() //服务第一次被创建的时候执行的方法
public void onDestroy() //服务被销毁时执行的方法
public int onStartCommand //服务运行时执行的方法
4) 服务启动与销毁
- Bind服务开启方式
在start中添加一些方法
1) public class MyBinder extends Binder{//在服务中添加一个内部类,用来实现一定功能
public void wodefuwu() {
Log.i("服务", "调用功能");
}
}
2) //让此方法返回我们的功能类
public IBinder onBind(Intent arg0) {
return myBinder;
}
3) 在活动中创建一个绑定继承ServiceConnection
继承两个方法
public class MyConn implements ServiceConnection {
//当绑定成功时的动作
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
binder = (MyBinder) arg1;
}//当绑定解除时的动作
public void onServiceDisconnected(ComponentName arg0) {
4) bindService(intent, conn, BIND_AUTO_CREATE); //启动服务
if (conn == null) { 在启动服务之前判断绑定帮助类是否为空
conn = new MyConn();
}
5) unbingService //解除绑定