IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Android应用四大组件之服务

    FranzKafka95发表于 2023-09-12 11:51:38
    love 0
    Read Time:1 Minute, 27 Second

    服务概览

    服务(service)是指在后台长期运行而不提供界面交互的服务,service分为两种,可以依据其启动方式来进行区分:

    started(启动):应用程序组件通过调用startService方法启动服务时,程序就会处于started状态,当service处于started时,其生命周期与启动它的组件无关,其拥有自己的生命周期,除非其自身在执行完任务后调用stopSelf进行终止,或者由其他组件调用stopService方法停止。使用startService启动服务,接收到的回调为onStartCommand。

    bound(绑定):应用组件通过调用调用bindService方法启动服务后,服务即处于bound状态,触发的回调为onBind,处于bound状态的服务会在调用者退出时一并退出,当所有与服务绑定的client都销毁时,服务即终止,触发的回调为onUnBind。通过bindService启动的服务又分为前台服务(Foregroud Service)和后台服务(Background Service)。前台服务启动时会通过dialog向用户申请权限,而后台服务对用户是完全无感知的。

    这两种类型的service,其生命周期如下所示:

    服务实现

    服务实现遵循一定的规则。大致分为以下几个步骤:

    1.创建Service的子类,或继承其现有的子类(比较常用的如IntentService类)。在实现中,我们必须重写一些回调方法,从而处理服务生命周期的某些关键方面。我们需要重写的回调方法包括:

    onStartCommand:当应用中的其他组件启动服务时,即通过startService来启动服务,服务启动后即可在后台无限期运行,在服务结束后需要通过调用stopSelf或者stopService来停止服务。

    onBind:当另一个组件想要绑定服务,也就是通过调用bindService的接口来绑定,在该方法中,我们必须通过返回IBinder对象提供binder接口

    onCreate:首次创建服务时,在onStartCommand或onBind之前,会触发onCreate回调,在该回调内,我们应当完成服务初始化配置

    onDestroy:当我们不再需要使用服务,准备将其销毁时,会触发onDestroy回调,我们应当在onDestroy中执行清理工作。

    代码示例如下:

    public class ExampleService extends Service {
    
        @Override
        public void onCreate() {
           .....
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
           .....
        }
    
        @Override
        public void onDestroy() {
           .....
        }
    
        @Override
        public IBinder onBind(Intent intent) {
           .....
        }
    
     }

    2.类似于Activity,我们还需要在应用清单文件AndroidManifest.xml中配置service字段,如下所示:

    <manifest ... >
      ...
      <application ... >
          <service android:name=".ExampleService" />
          ...
      </application>
    </manifest>
    

    其中android:name字段用于指定该service对应的具体的名称,AndroidManifest.xml中可以配置的service内容具体可参考如下链接,这里摘录一些比较重要且常用的。

    android:enabled:确定系统是否可以实例化服务。如果可以实例化,则设为 "true",否则设为 "false",默认值为 "true"。

    android:exported:确定其他应用的组件是否可以调用服务或与之交互。如果可以,则设为 "true",否则设为 "false"。当该值为 "false" 时,只有同一个应用或具有相同用户 ID 的应用的组件可以启动服务或绑定到服务

    android:permission:用于指定启动服务或绑定到服务所需的权限的名称,如果没有向启动服务的调用方授予相关权限,将无法启动服务。

    启动服务

    前面已经讲过,启动服务有两种方式,即startService于bindService,前者适合让service长期后台运行,而后者通常绑定到应用的其他组件,其生命周期受所绑定的组件影响。这里将通过示例向大家展示如何启动服务。

    startService:

    startService(Intent  service);

    使用示例:

    startService(new Intent(this, ExampleService.class));

    bindService:

    bindService(Intent service, ServiceConnection conn,int flags);

    service:指需要绑定的服务

    conn:一个接口,需要实现两个回调onServiceConnected和onServiceDisconnected

    flags:一般选择BIND_AUTO_CREATE,当服务不存在时自动创建该服务,触发onCreate回调,如服务已存在,则触发onBind回调.

    使用示例:

    Intent intent = new Intent(this, ExampleService.class);
    bindService(intent, conn, Context.BIND_AUTO_CREATE);

    相对于startService,bindService实现会更复杂一些,这里将以Activity中启动service为例,通过bindService来启动服务:

    import android.content.Intent;
    import android.content.ServiceConnection;
    
    public class MainActivity extends Activity {
    	private ExampleService mService=null;
    	
    	private ServiceConnection conn = new ServiceConnection (){
    	@Override
            public void onServiceConnected(ComponentName name, IBinder binder) {
                  //通过ExampleService的内部内获取服务对象
                  //当我们通过bindService启动服务后,在onServiceConnected回调中赋值
                  ExampleService.myBinder mBinder=(ExampleService.myBinder) binder;
                  mService = mBinder.getService() ;
            }
            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        }
    
       //bindService调用,启动服务
       @Override
          protected void onCreate(Bundle savedInstanceState) {
    	     Intent intent = new Intent(this, ExampleService.class);
    	     bindService(intent,conn,Context.BIND_AUTO_CREATE);
        }
        //onDestroy时需要unbindService
        @Override
        protected void onDestroy() {
           if(mService!= null ){
              unbindService(mConnection);
           }
        }
    }
    

    Happy
    Happy
    1 100 %
    Sad
    Sad
    0 0 %
    Excited
    Excited
    0 0 %
    Sleepy
    Sleepy
    0 0 %
    Angry
    Angry
    0 0 %
    Surprise
    Surprise
    0 0 %

    The post Android应用四大组件之服务 first appeared on FranzKafka Blog.



沪ICP备19023445号-2号
友情链接