助力软件开发企业降本增效 PHP / java源码系统,只需一次付费,代码终身使用! 广告
1、服务(Service)是Android中实现程序后台运行的解决方案,非常适合去执行那些不需要和用户交互而且还要求长期运行的任务。 2、服务的运行不依赖于任何用户界面,即使程序被切换到后台,或用户打开了另外一个应用程序,服务仍然能够正常运行。 3、服务不是运行在一个独立的进程中,而是依赖于创建服务时所在的应用程序进程。 4、服务不会自动开启线程,所有的代码都是默认运行在主线程当中。 ```java // MyService.java public class MyService extends Service { public MyService() { } @Override public IBinder onBind(Intent intent) { return new DownloadBinder(); } class DownloadBinder extends Binder { public void startDownload() { } public int getProgress() { return 0; } } } ``` ```java // MainActivity.java private MyService.DownloadBinder mDownloadBinder; Intent intent = new Intent(this, MyService.class); // 1、startService startService(intent); // 2、bindService bindService(intent, new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mDownloadBinder = (MyService.DownloadBinder) service; } @Override public void onServiceDisconnected(ComponentName name) { } }, BIND_AUTO_CREATE); ``` **1、startService启动服务** 生命周期回调:onCreate -> onStartCommand 使用startService方法启动服务后,Activity就无法控制和获得服务的运行逻辑了; **2、bindService启动服务** 生命周期回调:onCreate -> onBind 使用bindService方法启动服务后,在ServiceConnection回调中可以获取到Service中onBind方法返回的IBinder对象的实例,可以通过IBinder实例来获取服务的状态及控制服务。 > 注意 当对一个服务既调用startService方法,又调用bindService方法时,只有同时调用stopService和unbindService方法,Service的onDestroy方法才会执行。