Android 服务详解-Service(本地服务)

一、服务简介

Service为四大组件之一(Android四大组件:Activity、Service、Content Provider和BroadcastReceiver),其地位和Activity一样重要,在开发中用的不多,但是又缺少不了,在求职面试也是必出的题目。

什么是Service,Service是一种可以在后台长时间运行的且不提供用户交互界面的应用组件。Service可由其他组件启动,启动后即使用户切换到其他应用或回到Home页,服务仍将在后台运行。

此外,可以通过bindService绑定到服务进行交互,甚至进行进程间通信(IPC)。常见的操作后台处理网络事务,文件处理,音乐播放等。

2、Service生命周期

2.1、创建-onCreate()

第一次创建服务时,系统会调用此方法,如果服务已运行,则不会再调用此方法了。

2.2、开始-onStartCommand()

请求启动服务时,通过startAervice()来调用此方法,方法执行后会在后台无限期的运行,知道调用stopSelf()或stopService()来停止服务。

2.3、绑定-onBind()

当通过调用bindService()来调用此方法时,会执行此方法。

2.4、销毁-onDestroy()

不再使用服务时,会调用此方法来销毁服务,释放资源,清理内存等;

2.5生命周期

Service的生命周期请看下图:
Android service 生命周期

3、Service的用法

3.1 startService

创建一个服务它需要继承Service,Service是所有服务的一个基类,首先创建一个MyService类:

class MyService : Service() {

    private var TAG:String = "MyService"

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG,"-----service onCreate")
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG,"-----service onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG,"-----service onDestroy")
    }

}

这里用的是kotlin语法,代码比较简单,重写了基类中的几个方法,在方法里面添加了日志输出。

下面创建一个布局文件activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <TextView android:layout_width="match_parent"
              android:layout_height="50dp"
              android:text="开启服务"
              android:textSize="15sp"
              android:textColor="@android:color/white"
              android:background="#32c1d1"
              android:gravity="center"
              android:id="@+id/tv_start"
    />

    <TextView android:layout_width="match_parent"
              android:layout_height="50dp"
              android:textColor="@android:color/white"
              android:text="关闭服务"
              android:gravity="center"
              android:textSize="14sp"
              android:background="#ff8500"
              android:id="@+id/tv_stop"
    />

</LinearLayout>

这个布局文件里面放了两个TextView,开启服务和关闭服务,当做按钮来使用;

在MainActivity中实现业务逻辑:

class MainActivity : AppCompatActivity() {

    private var tv_start:TextView?=null
    private var tv_stop:TextView?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv_stop = findViewById(R.id.tv_stop)
        tv_start = findViewById(R.id.tv_start)

        tv_start?.setOnClickListener {
            //开启服务
            startMyService()
        }
        tv_stop?.setOnClickListener {
            //停止服务
            stopMyService()
        }
    }

    /***
     * 开启服务
     */
    private fun startMyService(){
        var intent = Intent(this,MyService::class.java)
        startService(intent)
    }

    /***
     * 关闭服务
     */
    private fun stopMyService(){
        var intent = Intent(this,MyService::class.java)
        stopService(intent)
    }
}

在MainAcitivty中做了两件事:
1、实例化了两个按钮并绑定了点击事件;
2、实现了两个方法:一个用于开启服务,一个用于关闭服务;

Android的需要在AndroidManifest.xml中进行注册才可以正常使用,Service也不例外,接下来需要去AndroidManifest.xml中注册一下服务:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.wangpengfei.servicedemo">
    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <service android:name=".MyService">
        </service>
    </application>

</manifest>

到此为止编码任务完成了,运行一下看看成果:
Android Service
首先点击开启服务按钮看下LogCat:
Android 服务详解之-Service(本地服务)
再多点击几次看看LogCat输出的日志:
Android 服务详解之-Service(本地服务)
通过日志可以看出,当Service 运行后,在调用startService(),onCerate()不再被调用,而onStartCommand()每次都会被调用。

下面在点击关闭服务看看执行的是什么:
Android 服务详解之-Service(本地服务)
点击关闭服务,调用stopService()方法,Service 调用了onDestory(),Service就销毁了。下面我们在点击开启服务,服务的生命周期改怎么走呢?
Android 服务详解之-Service(本地服务)

3.2 bindService

到现在为止Service和Activity一直是各玩各的,activity想告诉Service给我放首歌现在是实现不了的,下面我们来改下MyService类:

class MyService : Service() {

    private var TAG:String = "MyService"
    private var playBinder = MyPlayBinder()

    override fun onBind(intent: Intent?): IBinder? {
        Log.d(TAG,"-----service onBind")
        return playBinder
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG,"-----service onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG,"-----service onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.d(TAG,"-----service onUnbind")
        return super.onUnbind(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG,"-----service onDestroy")
    }

    inner class MyPlayBinder : Binder(){

        fun play(){
            Log.d(TAG,"-----MyPlayBinder playing")
        }

        fun stop(){
            Log.d(TAG,"-----MyPlayBinder stoped")
        }

    }
}

在MyService类中添加了MyPlayBinder内部类,并重写了onBind,返回MyPlayBinder的实例,供外部使用。
MyPlayBinder中添加了两个方法,具体内容没有实现,有需要的可以自己显现。两方法很简单,方法里面都输出了一句话。

布局文件activity_main.xml添加了三个按钮绑定服务,来首歌和解绑服务:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <TextView android:layout_width="match_parent"
              android:layout_height="50dp"
              android:text="开启服务"
              android:textSize="15sp"
              android:textColor="@android:color/white"
              android:background="#32c1d1"
              android:gravity="center"
              android:id="@+id/tv_start"
    />

    <TextView android:layout_width="match_parent"
              android:layout_height="50dp"
              android:textColor="@android:color/white"
              android:text="关闭服务"
              android:gravity="center"
              android:textSize="14sp"
              android:background="#ff8500"
              android:id="@+id/tv_stop"
    />

    <TextView android:layout_width="match_parent"
              android:layout_height="50dp"
              android:textColor="@android:color/white"
              android:text="绑定服务"
              android:gravity="center"
              android:layout_marginTop="10dp"
              android:textSize="14sp"
              android:background="#00b042"
              android:id="@+id/tv_bind_service"
    />
    <TextView android:layout_width="match_parent"
              android:layout_height="50dp"
              android:textColor="@android:color/white"
              android:text="来首歌"
              android:gravity="center"
              android:textSize="14sp"
              android:background="#ff4401"
              android:id="@+id/tv_play"
    />
    <TextView android:layout_width="match_parent"
              android:layout_height="50dp"
              android:textColor="@android:color/white"
              android:text="解绑服务"
              android:gravity="center"
              android:textSize="14sp"
              android:background="#FF4081"
              android:id="@+id/tv_unbind_service"
    />

</LinearLayout>

MainAcitivity类:

class MainActivity : AppCompatActivity() {

    private var tv_start:TextView?=null
    private var tv_stop:TextView?=null

    private var tv_bind_service:TextView?=null
    private var tv_play:TextView?=null
    private var tv_unbind_service:TextView?=null

    private var myplayBinder:MyService.MyPlayBinder?=null

    private var connection = object:ServiceConnection{

        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            myplayBinder = service as MyService.MyPlayBinder
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv_stop = findViewById(R.id.tv_stop)
        tv_start = findViewById(R.id.tv_start)

        tv_bind_service = findViewById(R.id.tv_bind_service)
        tv_play = findViewById(R.id.tv_play)
        tv_unbind_service = findViewById(R.id.tv_unbind_service)

        tv_start?.setOnClickListener {
            //开启服务
            startMyService()
        }

        tv_stop?.setOnClickListener {
            //停止服务
            stopMyService()
        }

        tv_bind_service?.setOnClickListener {
            //绑定服务
            bindMyService()
        }
        tv_play?.setOnClickListener {
            //来首歌
            play()
        }
        tv_unbind_service?.setOnClickListener {
            //解绑服务
            unbindMyService()
        }
    }

    /***
     * 开启服务
     */
    private fun startMyService(){
        var intent = Intent(this,MyService::class.java)
        startService(intent)

    }

    /***
     * 关闭服务
     */
    private fun stopMyService(){
        var intent = Intent(this,MyService::class.java)
        stopService(intent)
    }

    /***
     * 绑定服务
     */
    private fun bindMyService(){
        var intent  = Intent(this,MyService::class.java)
        bindService(intent,connection,BIND_AUTO_CREATE)
    }

    /**
     * 播放音乐
     */
    private fun play(){
        if(myplayBinder!=null)
        {
            if(tv_play?.text.toString() == "来首歌"){
                myplayBinder?.play()
                tv_play?.text = "播放中"
            }else{
                myplayBinder?.stop()
                tv_play?.text = "来首歌"
            }

        }
    }

    /***
     * 解绑服务
     */
    private fun unbindMyService(){
        unbindService(connection)
    }
}

绑定服务的代码编码结束,点击运行看看效果:
Android 服务详解之-Service(本地服务)
界面有些花里胡哨,这不是重点,能看懂就可以了。

点击绑定服务按钮,看下LogCat有什么变化:
Android 服务详解之-Service(本地服务)
代码执行了onCreate -> onBind() 说明服务绑定成功了。绑定成功后就可以播放音乐了,点击来首歌看看:
Android 服务详解之-Service(本地服务)
通过日志可以看到调用了MyPlayBinder的play()方法,按钮的状态变成了播放中,在点击一次看看:
Android 服务详解之-Service(本地服务)
这时候状态又变成stoped.

下面我们点击解绑服务:
Android 服务详解之-Service(本地服务)

4、bindService与startService启动方式的区别

4.1、startService()方式启动:

1、如果服务已经启动,不会重复执行onCreate(),而会调用onStartCommand(),不会调用onBind()方法;
2、一旦服务器开启就跟调用者没有任何关系了,服务会一直在后台运行;

4.2、bindService()方式启动:

1、如果服务已经启动,不会重复执行onCreate(),会调用onBind()方法,不会调用onStartCommand()方法;
2、绑定服务后可以与服务进行通信交互;
3、不再使用时,需要调用unbindService()方法停止服务

源码下载地址:

github

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值