安卓中服务Service的详解

本文详细介绍了Android四大组件之一的服务(Service)。服务是一种在后台运行的应用组件,不提供用户界面,适用于执行耗时任务如网络操作、播放音乐等。文章解释了服务的两种状态:启动和服务绑定,以及其生命周期方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

四大组件之一:服务Service
一,定义
服务是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够开启Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个Service与之交互,例如,一个Service可能会处理网络操作,播放音乐,操作文件或者与内容提供者交互,所有这些操作都是在后台进行。
二,服务的两种状态
服务一旦被开启,如果不再使用就要停止或者解绑服务,否则它会一直在后台运行,占用内存,这里的服务不能靠系统自动通过gc操作清理内存的
1,启动的状态
startService(intent);
与stopService();停止服务搭配使用
2,绑定的状态
bindService(Intent service, ServiceConnection conn,int flags);与unbindService解绑服务搭配使用
三,服务的生命周期
startService方法启动的service
onCreate()--->onStartCommand()-->onStart()--->onDestory()
绑定Service方法启动service
bindService(Activity中绑定服务)——》onCreate()--->onBind(绑定的Service)
——》MyBinder myBinder = new MyBinder();——》ServiceConnection实现这个链接拿到代理人对象
———》onServiceConnected()拿到MyBinder这个对象————》调用Service里面的方法————》destory();
简单理解为:
onCreate()-->onBind()--->Clients are bound to service-->onUnbind()--->onDestory()

四,服务的应用步骤
(1)首先得在清单文件中去进行声明
(2)在java代码中开启服务
Intent intent = new Intent(this,PhoneStatusService.class);
startService(intent);
Intent intent = new Intent(this,PhoneStatusService.class);
stopService(intent);
五,服务创建的步骤:
(1)绑定服务状态
1,新建一个类继承Service,并在这个类中创建一个内部类代理人对象继承自Binder对象,提供一个方法,可以间接调用服务的方法。
ublic class TestService extends Service {
class MyBinder extends Binder{

        public void callShow(){
        show();
    }
}
show()为服务里面的方法
2,重写服务里的onBind方法,返回的是中间人对象
public IBinder onBind(Intent intent) {
        System.out.println("2. 如果服务被成功绑定,就会调用onbind方法,返回一个代理人对象");
        MyBinder myBinder = new MyBinder();
        System.out.println("3. new出来代理人对象"+myBinder.toString());
        return myBinder;
    }
3,在activity中绑定服务
public void bind(View v){
    Intent intent = new Intent(this,TestService.class);
    MyConn conn = new MyConn();
    bindService(intent, conn, Context.BIND_AUTO_CREATE);
}


4,在服务成功绑定的时候,会执行onServiceConnected方法传递过来一个IBinder对象,强制类型转化,调用接口里面的方法
private class MyConn implements ServiceConnection{
    @Override
    public void onServiceConnected(ComponentName arg0, IBinder service) {
        myBinder = (MyBinder) service;
    }
(2)启动服务状态
1,在清单文件中注册服务
2,新建一个类继承自服务对象
2,在activity中开启服务





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值