Android--Service

Service

Service简介

Service提供了两个主要的功能:

  1. 可以让程序在后台一直做它想要做的事情,即使当前没有与用户进行交互。(对应context.startService()的启动方式)。
  2. 实现了某些功能已供其他程序调用的工具,并可保持长期连接进行交互。(对应context.bindService()的启动方式)。

Service生命周期

  1. 启动服务
    1. 启动服务:startService()
    2. 单次创建:onCreate()->onStartCommand()
    3. 多次创建:onCreate()->onStartCommand()->onStartCommand()
    4. 停止服务:stopService()
    5. 结束服务:onDestroy()
  2. 绑定服务
    1. 绑定服务 bindService():onCreate() —> onBind()
    2. 解绑服务 unbindService():onUnbind() —> onDestroy()
  3. 先启动后绑定
    1. 启动服务:startService()后绑定服务bindService()
      onCreate() —> onStartCommand() —> onBind()
    2. 先停止服务stopService()后解绑服务unbindService()
      onUnbind() —> onDestroy()
  4. 先绑定后启动
    1. 先绑定服务bindService()后启动服务startService()
      onCreate() —> onBind() —> onStartCommand()
    2. 先解绑服务unbindService()后停止服务stopService()
      onUnbind() —> onDestroy()
  5. 先解绑再绑定
    1. 先解绑服务unbindService()再绑定服务bindService()
      onUnbind() —> onRebind()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jnMkgj28-1626421930162)(/home/ts/.config/Typora/typora-user-images/image-20210716151111438.png)]

Service使用

  1. Service文件

    public class MyService extends Service {
        private static final String TAG = "MyService";
    
        private DownloadBinder mBinder = new DownloadBinder();
    
    
        class DownloadBinder extends Binder{
            public void startDownload(){
                Log.d(TAG,"startDownload");
            }
            public int getProgress(){
                Log.d(TAG,"getProgress");
                return 0;
            }
        }
    
        public MyService() {
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.d(TAG, "onCreate");
        }
    
        @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");
        }
    
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.d(TAG, "onUnbind");
            return super.onUnbind(intent);
        }
    
        @Override
        public void onRebind(Intent intent) {
            super.onRebind(intent);
            Log.d(TAG, "onRebind");
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            return mBinder;
        }
    }
    
  2. MainActivity

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
        private static final String TAG = "MainActivity";
    
        private MyService.DownloadBinder downloadBinder;
    
        private ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                downloadBinder = (MyService.DownloadBinder) service;
                downloadBinder.startDownload();
                downloadBinder.getProgress();
            }
    
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.d(TAG, "onServiceDisconnected");
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button startService = findViewById(R.id.start_service);
            Button stopService = findViewById(R.id.stop_service);
            Button bindService = findViewById(R.id.bind_service);
            Button unbindService = findViewById(R.id.unbind_service);
            startService.setOnClickListener(this);
            stopService.setOnClickListener(this);
            bindService.setOnClickListener(this);
            unbindService.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.start_service:
                    Intent startIntent = new Intent(this,MyService.class);
                    startService(startIntent);
                    break;
                case R.id.stop_service:
                    Intent stopIntent = new Intent(this,MyService.class);
                    stopService(stopIntent);
                    break;
                case R.id.bind_service:
                    Intent bindIntent = new Intent(this,MyService.class);
                    bindService(bindIntent,connection,BIND_AUTO_CREATE);
                    break;
                case R.id.unbind_service:
                    unbindService(connection);
                    break;
                default:
                    break;
            }
        }
    }
    

IntentService

1.什么是IntentService

		android.app.IntentService 的本质就是一个 android.app.Service。它需要在 AndroidManifest.xml 中注册 <service /> 节点,并可以 startService() 的形式启动。它是Android官方引入的用于执行“耗时任务”的服务抽象类。
		传统的 Service 里的代码都是运行在主线程里的,而对于服务这种天生就被设计成更适合“在后台默默工作”的机制来说,我们又常常需要它执行一些耗时型的操作,主线程是不建议做耗时操作的。因此,我们常常会在服务中创建子线程来做耗时操作。而IntentService就是Android官方提供的在普通Service里搭建好了用于执行耗时任务的子线程的特殊Service。

2.IntentService的原理

		IntentService的本质就是一个普通Service里面加装了一套运行在子线程的Handler机制。可以看IntentSerivce的源码进行深入了解。

3.IntentService的使用

		IntentService的启动和普通的service一致,onHandleIntent(Intent intent)是执行在子线程中的,所以我们可以把耗时操作放在这个回调中。其他的生命周期都是在主线程当中,我们连续调用了五次startService(intent)之后,onStartCommand依次被调用了五次,然后依次执行了onHandleIntent五次,这样就依次完成了job,当最后一个job完成,也就是在最后一次onHandleIntent调用完成之后,整个IntentService的工作都完成,执行onDestroy回调方法,IntentService销毁。所以IntentService在onHandleIntent执行完成后是会自动销毁的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

立花泷える宫水三叶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值