Service —(服务)

概述:

Service(服务)是一个一种可以在后台执行长时间运行操作而没有用户界面的应用组件。服务可由其他应用组件启动(如Activity),服务一旦被启动将在后台一直运行,即使启动服务的组件(Activity)已销毁也不受影响。
(1)不同点:
Activity : 可以和用户交互, 页面可见。
Service : 后台运行, 没有界面。
(2)相同点:
在清单文件中注册, 都有自己的生命周期。

此外,组件可以绑定到服务,以与之进行交互,甚至是执行进程间通信 (IPC)。 例如,服务可以处理网络事务、播放音乐,执行文件 I/O 或与内容提供程序交互,而所有这一切均可在后台进行,Service基本上分为两种形式:

startService

bindService

Service特点:

service在后台运行,不用与用户进行交互。即使应用退出,服务也不会停止。
当应用进程被杀死时,服务便会停。
service运行在主线程中,当需要执行耗时操作的时候,需要在服务中创建子线程完成。
service 的用途:播放音乐、后台下载大文件等。

Service的启动方式以及生命周期

生命周期
生命周期流程
onCreate():

首次创建服务时,系统将调用此方法。如果服务已在运行,则不会调用此方法,该方法只调用一次。

onStartCommand():

当另一个组件(如 Activity)通过调用 startService() 请求启动服务时,系统将调用此方法。一旦执行此方法,服务即会启动并可在后台无限期运行。 如果自己实现此方法,则需要在服务工作完成后,通过调用 stopSelf() 或 stopService() 来停止服务。(在绑定状态下,无需实现此方法。)

onDestroy():

当服务不再使用且将被销毁时,系统将调用此方法。服务应该实现此方法来清理所有资源,如线程、注册的侦听器、接收器等,这是服务接收的最后一个调用。

onBind():

当另一个组件想通过调用 bindService() 与服务绑定,系统将调用此方法。在此方法的实现中,必须返回 一个IBinder 接口的实现类,供客户端用来与服务进行通信。无论是启动状态还是绑定状态,此方法必须重写,但在启动状态的情况下直接返回 null。

onUnbind():

当另一个组件通过调用unbindService()与服务解绑时,系统将调用此方法。

onRebind():

当旧的组件与服务解绑后,另一个新的组件与服务绑定,onUnbind()返回true时,系统将调用此方法。

手动调用:

启动——startService()
关闭——stopService()
绑定——bindService()
解绑——unbindService()

自动调用:

创建——onCreat()
开始——onStartCommand()
销毁——onDestroy()
绑定——onBind()
解绑——onUnbind()

启动方式一 (startService)

1、右键创建一个Service ,会自动在清单文件中创建,和Activity一样。

public class MyService extends Service {
    private static final String TAG = "MyService";

    public MyService() {
        Log.i(TAG, "MyService:++");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind:++");
        return null;
    }
}

2、在xml中布局
设置两个按钮,一个启动、一个停止

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/create_server_id"
        android:text="启动一个服务"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/stop_server_id"
        android:text="停止一个服务"
        />
</LinearLayout>

3、MainActivity内容

public class MainActivity extends AppCompatActivity {
    private Button createServerId;
    private Button stopServerId;
    private Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        stopServerId = findViewById(R.id.stop_server_id);
        createServerId = findViewById(R.id.create_server_id);

        stopServerId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(intent);
            }
        });

        createServerId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);
            }
        });
    }
}
如果服务已经开启,就不会重复的执行 onCreate() ,而是调用 onStart() 或 onStartCommand()。而服务停止的时候调用 onDestory()

一旦服务开启跟开启者就没有任何关系;
开启者退出之后,服务还是可以在后台长期运行的。前提是没有调用 stopService(Intent);
开启者不能调用服务里面的方法;

总结:

启动方式:onCreate() — onStartCommand() — onDestroy()
开启服务:startService()
停止服务:stopService()

启动方式二 (bindService)

使用Service的步骤如下:

1,定义一个Service类,并继承 Service
2,在 AndroidManifest.xml 中配置此 Service
3,使用 Context 的 bindService(Intent, ServiceConnection, int) 方法来启动此 Service
4,不使用该服务时,调用 unbindService(ServiceConnection) 方法停止此 Service

绑定服务不会调用 onStart() 或 onStartCommand() 方法。
注意:同一个服务, 只能被同一个启动源, 绑定一次, 除非解绑后, 可以再次绑定
特点:

bind的方式开启服务,绑定服务,调用者挂了,服务也会跟着挂掉。
绑定者可以调用服务里面的方法。

1、创建服务:自定义Service类继承Service

public class MyService extends Service {
    @Nullable
    @Override
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: ");
        return new MyBinder();
    }

    public class MyBinder extends Binder{
        public void callShow(){
            show();
        }
    }

    public void show(){
        Log.i(TAG, "show:++");
    }
    //服务中提供的方法
    public void methodOne(){
        Toast.makeText(this, "methodOne", Toast.LENGTH_SHORT).show();
    }
    //服务中提供的方法
    public void methodTwo(){
        Toast.makeText(this, "methodTwo", Toast.LENGTH_SHORT).show();
    }
}

2、清单文件注册服务

<service android:name=".MyService"></service>

3、绑定服务和解除绑定

public class MainActivity extends AppCompatActivity {
    private Intent intent;//开启服务的意图对象
    private MyService myService;//通过绑定获取Service
    //绑定服务连接
    private ServiceConnection connection=new ServiceConnection() {
       @Override
       public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected: ");
            MyService.MyBinder binder = (MyService.MyBinder) service;
            binder.callShow();
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.绑定服务
        intent =new Intent(this,MyService.class);
        //参数一:intent意图  参数二:绑定服务连接  参数三:flag标记BIND_AUTO_CREATE 绑定的时候自动创建服务
        bindService(intent,connection, Service.BIND_AUTO_CREATE);
    }
    //2.解除绑定服务
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
    //3.点击按钮调用服务的方法
    public void methodOne(View view){
        myService.jiehun();
    }
    
}

总结:

绑定方式:onCreate() – onBind() — onUnbind() — onDestroy()
绑定服务:bindService()
解除绑定:unbindService()

两种的启动服务的特点:
第一种,一旦启动,只能手动停止。
第二种,可以调用服务里的方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,612评论 5 471
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,345评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,625评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,022评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,974评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,227评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,688评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,358评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,490评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,402评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,446评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,126评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,721评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,802评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,013评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,504评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,080评论 2 341

推荐阅读更多精彩内容