Service的简单使用

今天在网上看了一下Service,把用法简单记录下来:

  • Service简介
    Service是Android的四大组件之一,和activity级别差不多,但不能页面显示,只能在后台运行,可以与其他组件进行交互,需要在清单文件进行注册。
  • Service的创建和注册
    1.Service服务的创建
    服务的创建必须要重写onBind方法。
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "MyService.onBind: ");
        return null;
    }

2.Service服务的注册,在AndroidManifest中注册
服务的创建必须要重写onBind方法。

<service android:name=".MyService" />
  • Service两种启动模式
    1.Context.startService()
    (1)启动服务startService : –>onCreate()–> onStart()
    (2)停止服务stopService : –>onDestroy()

    如果调用者直接退出而没有停止Service,则Service 会一直在后台运行。这里的退走只是关闭了UI界面。
    startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方 法,接着调用onStart()方法。如果调用startService()方法前服务已经被创建,多次调用 startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。采用 startService()方法启动的服务,只能调用stopService()方法结束服务,服务结束时会调用生命周期的onDestroy()方法。

    2.Context.bindService()
    (1)绑定bindService : –> onCreate() –> onBind()
    (2)解绑unbindService: –>onUnbind()
    (3)正常停止程序服务的方法是先解绑unbindService,再停止服务stopService。
    (4)如果绑定后调用stopService 方法,这时是不能停止服务的,如果这时再调用解绑unbindService,程序后先解绑,后停止服务。

    用bindService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate() 方法,接着调用onBind()方法。这个时候调用者和服务绑定在一起,调用者退出了,系统就会先调用服务的onUnbind()方法,接着调用onDestroy()方法。如果调用bindService()方法前服务已经被绑定,多次调用bindService()方法并不会导致多次创建服务及绑定(也就是说 onCreate()和onBind()方法并不会被多次调用)。如果调用者希望与正在绑定的服务解除绑定,可以调用unbindService()方法,调用该方法也会导致系统调用服务的onUnbind()->onDestroy()方法。 
    

绑定Service方法:bindService(intent,conn,Service.BIND_AUTO_CREATE);
第一个:Intent对象
第二个:ServiceConnection对象,创建该对象要实现它的onServiceConnected()和 on ServiceDisconnected()来判断连接成功或者是断开连接
第三个:创建Service的模式,一般指定绑定的时候自动创建

  • 代码
    MainActivity,通过四个按钮实现开始,结束,绑定,解绑服务的功能
package com.example.xll.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Button buttonStart,buttonStop,buttonBind,buttonUnbind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStart = (Button) findViewById(R.id.button_start);
        buttonStop = (Button) findViewById(R.id.button_stop);
        buttonBind = (Button) findViewById(R.id.button_bind);
        buttonUnbind = (Button) findViewById(R.id.button_unbind);

        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
        buttonBind.setOnClickListener(this);
        buttonUnbind.setOnClickListener(this);
    }

    //服务绑定的连接对象
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    //服务绑定的标识
    //BIND_AUTO_CREATE 绑定的同时,启动Service
    private int flags = Service.BIND_AUTO_CREATE;

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.button_start:
                //开启服务需要Intent对象,和Activity跳转类似
                startService(new Intent(this, MyService.class));
                break;
            case R.id.button_stop:
                //停止服务的方法
                stopService(new Intent(this, MyService.class));
                break;
            case R.id.button_bind:
                //绑定服务
                bindService(new Intent(this, MyService.class), conn, flags);
                break;
            case R.id.button_unbind:
                //防止在没有绑定的情况下,去解除绑定,抛出异常
                try {
                    //解除绑定
                    unbindService(conn);
                } catch (Exception e) {
                     Log.e("onClick: ", "MainActivity.unBindService"+e);
                }
                break;
            default:

                break;
        }
    }
}

MyService,继承Service

package com.example.xll.service;

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

/**
 * 功能: * 服务的创建,
         * 测试生命周期的过程和先后
         * 五个生命周期:
         * onCreate
         * onStartCommand
         * onDestroy
         * onBind
         * onUnBind
 * 作者:xll
 * 日期:2016/11/14
 * 邮箱:liangliang.xu1110@gmail.com
 */

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

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

    @Override
    public void onCreate() {
        Log.i(TAG, "MyService.onCreate: ");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "MyService.onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "MyService.onDestroy: ");
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "MyService.onUnbind: ");
        return super.onUnbind(intent);
    }
}

布局文件,只有四个Button

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.xll.service.MainActivity">

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

    <Button
        android:text="停止服务"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_stop"/>

    <Button
        android:text="绑定服务"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_bind"/>

    <Button
        android:text="解绑服务"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_unbind"/>
</LinearLayout>

程序运行后的界面
这里写图片描述

点击启动服务
这里写图片描述
调用onCreate,onStartCommand

点击停止服务
这里写图片描述
调用onDestory

点击绑定服务
这里写图片描述
调用onCreate,onBind,在绑定服务的情况下是不能停止服务的,要解绑服务才能停止服务。
这里写图片描述
在程序的服务启动/绑定了的情况下,再点击启动服务,只会回调onStartCommand方法,也就是说一个服务在一个生命周期内只会回调一次onCreate方法。

点击解绑服务
这里写图片描述
调用onUnbind,onDestory

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值