Android四大组件之Service的基本用法

本文详细讲解了Android服务的创建、启动、停止、通信及生命周期管理,包括如何利用IntentService进行异步任务处理,以及如何创建前台服务防止被系统回收。

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

1.创建一个服务

服务是一个类,我们自己定义的服务都是继承自Service的,假设创建一个MyService类,代码如下:

public class MyService extends Service{
    
    public MyService(){
    }
    
    @Override
    public IBinder onBind(Intent intent){
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate(){
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
    }
}

MyService类中重写了4个方法:

(1)onBind():该方法在使用BindService()方法启动服务时被调用,用于绑定活动和服务。

(2)onCreate():该方法在服务被创建的时候调用。

(3)onStartCommand():该方法会在每次服务被启动的时候调用。

(4)onDestroy():该方法在服务被销毁的时候调用。

2.启动和停止服务

启动和停止服务都是借助Intent来实现的,代码如下:

Intent startIntent = new Intent(this,MyService.class);
startService(startIntent);//启动服务
Intent stopIntent = new Intent(this,MyService.class);
stopService(stopIntent);//停止服务

注:可以在MyService类中的任何一个位置调用stopSelf()方法也能让服务停止下来。

3.活动和服务进行通信

在活动中通过startService()方法启动一个服务之后,服务就会自动运行,但是之后活动就无法控制该服务了,活动无法和该服务进行通信,告知服务需要做什么事等等。为了实现活动和服务之间能够进行通信,需要用bindService()方法启动服务。

1.修改服务类代码如下:

public class MyService extends Service{
    
    public MyService(){
    }

    class DownloadBinder extends Binder{//创建一个类继承自Binder,类中有两个方法

        public void startDownload(){
        }

        public int getProgress(){
        }
    }

    private DownloadBinder mBinder = new DownloadBinder();//创建类实例

    
    
    @Override
    public IBinder onBind(Intent intent){
        return mBinder;//返回类实例
    }

    @Override
    public void onCreate(){
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
    }
}

MyService类中新建了一个DownloadBinder类,该类提供了两个方法可供使用。并且创建了一个DownloadBinder类的实例,最后在onBind()方法中将该实例返回。

2.活动的代码如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    
    private MyService.DownloadBinder downloadBinder;//创建一个DownloadBinder变量
    
    private ServiceConnection connection = new ServiceConnection(){
        
        @Override
        public void onServiceDisconnected(ComponentName,IBinder service){
        }

        @Override
        public void onServiceConnected(ComponentName,IBinder service){
            downloadBinder = (MyService.DownloadBinder) service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState){
        ...
        Intent bindIntent = new Intent(this,MyService.class);
        bindService(bindIntent,conncetion,BIND_AUTO_CREATE);//绑定服务
        ...
        unbindService(connection);//解除绑定

活动中创建了一个ServiceConnection的匿名类,类里面重写了两个方法,这两个方法分别会在活动与服务成功绑定以及解除绑定的时候调用。当活动成功绑定服务时,调用的是onServiceConnected()方法,方法内通过向下转型得到了DownloadBinder的实例,之后就可以调用DownloadBinder类提供的两个方法了。

4.服务的生命周期

(1)调用startService()方法启动:一旦在活动中的任何位置调用了startService()方法,相应的服务就会启动,之后就会调用服务的onStartCommand()方法,倘若是第一次调用startService()方法启动服务,就会先调用服务的onCreate()方法创建该服务,然后再调用onStartCommand()方法启动服务。每调用一次startService()方法就会回调一次onStartCommand()方法,但不管调用了多少次startService()方法,只需要调用一次stopService()方法或者stopSelf()方法就能停止服务。

(2)调用bindService()方法启动:倘若调用bindService()方法来启动服务,就会调用服务的onBind()方法,倘若是第一次调用bindService()方法启动服务,就会先调用服务的onCreate()方法创建该服务,然后再调用onBind()方法启动服务。onBind()方法会返回一个IBinder对象的实例,该实例作为参数返回给活动中ServiceConnection匿名类的onServiceConnected()方法,这样就能实现活动和服务的通信了。但不管调用了多少次bindService()方法,只需要调用一次unbindService()方法就能停止服务,但是unbindService()方法只能调用一次,调用多次就会弹出异常。

(3)两个方法都调用:如果既调用了startService()方法,又调用了bindService()方法,就需要同时调用stopService()方法和unbindService()方法来注销服务,否则onDestroy()方法不会被调用。

5.使用IntentService

由于服务中的代码是运行在主线程中的,如果服务需要处理一些耗时的逻辑,就应该在服务的每个具体的方法内开启子线程,在子线程中处理耗时逻辑,并且在处理完之后调用stopSelf()方法来停止服务。为此,Android专门提供了一个IntentService类来创建一个异步的、会自动停止的服务。首先创建一个MyIntentService类继承自IntentService,代码如下:

public class MyIntentService extends IntentService{
     
    public MyIntentService(){
        super("MyIntentService");//调用父类的有参构造函数
    }

    @Override
    protected void onHandleIntent(Intent intent){//该方法在子线程中运行
        //耗时逻辑
    }
}

MyIntentService类中不再是onCreate()方法和onStartCommand()方法,而是onHandleIntent()方法,在该方法中处理耗时逻辑,并且该方法是在子线程中运行的。

使用方法同普通服务类:

Intent intentService = new Intent(this,MyIntentService.class);
startService(intentService);

6.开启前台服务

前台服务不会被系统回收掉,开启前台服务的方法是在服务类的onCreate()方法内构建一个Notification对象notification,然后startForeground(1,notification)即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值