Android四大组件之服务

服务

服务是Android中实现程序后台运行的解决方案,它非常合适去指向那些不需要与用户交互而且还要长期运行的任务,服务在后台运行,不依赖于任何界面,然而服务并不是运行在一个独立的进程当中,而是依赖于创建服务时所在的应用程序进程,当某个应用程序进程被杀掉时,所依赖于该进程的服务也会停止进行。

创建服务

在包中新建服务类:new->service->service
新建服务类,继承service类,重写三个方法,分别为
onCreate(),onStartCommon(),onDestroy(),onBind(),分别在创建服务,启动服务,关闭服务和活动与服务进行通信时调用
android studio自动在AndroidManifest中注册了service(包含exported与enable两个属性)

开启和关闭服务

//开启服务
 Intent startService = new Intent(this,MyService.class);
                startService(startService);
//关闭服务
Intent stopService = new Intent(this,MyService.class);
                stopService(stopService);

MyService类

public class MyService extends Service {

    private static final String TAG = "MyService";
    
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
        
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
       
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }
}

点击按钮,开启服务
startService关闭服务
stopService注意:onCreate()方法在服务第一次创建时调用,而onStartCommon()在每一次启动时调用,之后无论点击多少次start service按钮,均只会调用onStartCommon()方法

活动与服务进行通信

活动与服务想要通信,需要借助Binder类和onBind()方法实现,在自定义service类中创建内部类MyBinder类继承Binder类,在MyBinder中实现服务与活动通信的逻辑。以下载功能为例:

  • 新建服务类MyService,继承Service类
public class MyService extends Service {

    private static final String TAG = "MyService";
     
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");     
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }
}
  • 在MyService类中, 新建DownloadBinder类,继承Binder类,并定义DownloadBinder对象
public DownloadBinder mBinder = new DownloadBinder();
    //在Binder类中实现活动与服务进行通信的逻辑
    public class DownloadBinder extends Binder{
        public void startDownload(){//开始下载
            Log.d(TAG, "startDownload executed");
        }

        public int getProgress(){//下载进度
            Log.d(TAG, "getProgress executed");
            return 0;
        }
    }
  • 修改onBinder()方法返回值
@Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return mBinder;
    }
  • 在MainActivity中创建ServiceConnection变量,通过匿名类初始化,并实现两个方法:
private ServiceConnection connection = new ServiceConnection() {
        //当活动与服务绑定成功时调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (MyService.DownloadBinder) service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
            Log.d(TAG, "onServiceConnected executed ");
        }

        //在服务异常销毁时调用此方法,如内存不足
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected executed");
        }
    };
  • 在需要的地方添加绑定服务事件与解绑事件
 Intent bindService = new Intent(this,MyService.class);
 //绑定服务,BIND_AUTO_CREATE常量表示在绑定时创建服务,此时会调用onCreate()而不会调用onStartCommon()
                bindService(bindService,connection,BIND_AUTO_CREATE);
 Intent unbindService = new Intent(this,MyService.class);
                unbindService(connection);//解绑服务

服务的生命周期

startServiceLifeCircle
bindServiceLifeCircle
当调用了startService()后又调用了bindService(),销毁服务时,需要调用stopService()和unbindService()两个方法才能销毁该服务
在这里插入图片描述

服务的更多技巧

前台服务

IntentService

服务的最佳实践——完整版的下载示例

猜你喜欢

转载自blog.csdn.net/HuangGang_clown/article/details/84862387