Android service服务详解

为什么要写服务这篇文章

1.被老员工喷了
2.自己犯贱,捡西瓜丢芝麻,该打,555

服务是啥

服务是一个应用程序组件,可以在后台执行长时间运行,不提供用户界面。一个应用程序组件可以启动一个服务,它将继续在后台运行,即使用户切换到另一个应用程序。此外,一个组件可以绑定到一个服务与它交互,多个主键也可以绑定同一个服务,甚至执行进程间通信(IPC)。例如,一个服务可能处理网络通信、播放音乐、计时操作或与一个内容提供者交互等等,都在后台执行。

服务的类型

其实可以按照3种方式分
我就只按使用方式分了
1.startService启动的服务:主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopService。
2.bindService启动的服务:方法启动的服务要进行通信。停止服务使用unbindService。
3.同时使用startService、bindService 启动的服务:停止服务应同时使用stopService与unbindService。

服务的生命周期

在这里插入图片描述
他们的方法
一、调用方法

方法名作用
startService()启动服务
stopService()关闭服务
bindService()绑定服务
unbindService()解绑服务

二、生命方法

方法名作用
onCreat()启动服务
onStartCommand()开始服务
onBind()绑定服务
onUnbind()解绑服务
onDestroy()销毁服务

这当中还是有一个onRebind()方法
onRebind()方法被调用还有个前提是先前的onUnbind()方法返回值为true

生命周期的调用

1)启动Service服务
单次:startService() —> onCreate() —> onStartCommand()
多次:startService() —> onCreate() —> onStartCommand() —> onStartCommand()
2)停止Service服务
stopService() —> onDestroy()
3)绑定Service服务
bindService() —> onCreate() —> onBind()
4)解绑Service服务
unbindService() —> onUnbind() —> onDestroy()
5)启动绑定Service服务
startService() —> onCreate() —> onStartCommand() —> bindService() —> onBind()
6)解绑停止Service服务
unbindService() —> onUnbind() —> stopService() —> onDestroy()
7)解绑绑定Service服务
unbindService() —> onUnbind(ture) —> bindService() —> onRebind()

最后附上实验Demo

MainActivity.class
package com.yuexia.myservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener{
    private boolean isBound = false;
    private Intent intent;
    private MyBroadcastReceiver mBroadcastReceiver;
    private LocalBroadcastManager localBroadcastManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent = new Intent(this,TextService.class);
        initView();
    }
    private void initView() {
        Button btn_start=(Button) this.findViewById(R.id.btn_start);
        Button btn_close=(Button) this.findViewById(R.id.btn_close);
        Button btn_bundle=(Button) this.findViewById(R.id.btn_bundle);
        Button btn_unbundle=(Button) this.findViewById(R.id.btn_unbundle);
        btn_start.setOnClickListener(this);
        btn_close.setOnClickListener(this);
        btn_bundle.setOnClickListener(this);
        btn_unbundle.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.btn_start :
                startService(intent);
                break;

            case R.id.btn_close :
                stopService(intent);
                break;

            case R.id.btn_bundle :
                isBound = bindService(intent, serviceConnection,  Context.BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbundle :
                if (isBound) {
                    unbindService(serviceConnection);
                    isBound = false;
                }
                break;
        }
    }
    // 在Activity中,我们通过ServiceConnection接口来取得建立连接与连接意外丢失的回调
    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service){
            // 建立连接
            // 获取服务的操作对象
            TextService.MyBinder binder = (TextService.MyBinder)service;
            binder.getService();// 获取到的Service即MyService
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 连接断开
        }
    };
}

TextService.class
package com.yuexia.myservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by syt98 on 2018/12/20.
 */

public class TextService  extends Service{
    private static final String TAG = "TextService";
    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: 创建服务");
        super.onCreate();
        // The service is being created
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: 开始服务");
        return super.onStartCommand(intent, flags, startId);
        // The service is starting, due to a call to startService()
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: 绑定服务");
        return new MyBinder();
        // A client is binding to the service with bindService()
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind: 解绑服务");
        return super.onUnbind(intent);
        // All clients have unbound with unbindService()
    }

    @Override
    public void onRebind(Intent intent) {
        Log.d(TAG, "onRebind: 从新绑定");
        super.onRebind(intent);
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy: 销毁服务");
        super.onDestroy();
        // The service is no longer used and is being destroyed
    }
    // IBinder是远程对象的基本接口,是为高性能而设计的轻量级远程调用机制的核心部分。但它不仅用于远程
    // 调用,也用于进程内调用。这个接口定义了与远程对象交互的协议。
    // 不要直接实现这个接口,而应该从Binder派生。
    // Binder类已实现了IBinder接口
    class MyBinder extends Binder {
        /**
         * 获取Service的方法
         * @return 返回PlayerService
         */
        public  TextService getService(){
            return TextService.this;
        }
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yuexia.myservice">
    
    <uses-permission android:name="android.permission.INTERNET"/>
    
    <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=".TextService"
            android:exported="true"
            android:label="TextService" />
            
    </application>
    
</manifest>
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"
    <Button
        android:layout_weight="1"
        android:id="@+id/btn_start"
        android:text="开启服务"
        android:layout_width="0dp"
        android:layout_height="wrap_content" />
    <Button
        android:layout_weight="1"
        android:id="@+id/btn_close"
        android:text="关闭服务"
        android:layout_width="0dp"
        android:layout_height="wrap_content" />
    <Button
        android:layout_weight="1"
        android:id="@+id/btn_bundle"
        android:text="绑定服务"
        android:layout_width="0dp"
        android:layout_height="wrap_content" />
    <Button
        android:layout_weight="1"
        android:id="@+id/btn_unbundle"
        android:text="解绑服务"
        android:layout_width="0dp"
        android:layout_height="wrap_content" />
</LinearLayout>

本章有很多内容引用了
https://www.jianshu.com/p/1e49e93c3ec8
https://www.jianshu.com/p/cc25fbb5c0b3
关于Android8.0 启动后台Service的话请看
https://www.jianshu.com/p/71e16b95988a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值