服务(Service)

服务

服务作为Android的四大组件之一,它不像活动那么清晰可见,总是在后台默默的付出。下面让我们浅显易懂的学习以下服务。

1.启动形式

1.直接启动

通过startService启动服务,这种启动形式比较简单;

  • 创建服务
public class MyService extends Service {

    public static final String  TAG= "MyService";

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

    @Override
    public void onCreate() {
        Log.d(TAG,"onCreate()");
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       Log.d(TAG,"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

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

  • 创建布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/start"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="开启事务"/>

    <Button
        android:id="@+id/stop"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="停止服务" />
</LinearLayout>
</LinearLayout>
  • 启动服务
public class MyService extends Service {

    public static final String  TAG= "MyService";


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

    @Override
    public void onCreate() {
      Log.d(TAG,"onCreate()");
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       Log.d(TAG,"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG,"onDestroy()");
        super.onDestroy();
    }
}
  • 在AndroidManfest.xml中声明
<service android:name=".MyService"/>

注意:1.服务需要继承Service,onbind()必须被重写;

​ 2.服务需要在配置文件中配置;

2.绑定启动

  • 创建服务
package com.example.myservice;

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

import androidx.annotation.Nullable;

public class MyService extends Service {

    public static final String  TAG= "MyService";
    
    private Mybind mybind = new Mybind();
    
    class Mybind extends Binder{
        public void start(){
            Log.d(TAG,"Mybind.start()");
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG,"onBind(Intent intent)");
        return mybind;
    }

    @Override
    public void onCreate() {
        Log.d(TAG,"onCreate()");
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       Log.d(TAG,"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

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

可以看到onBind()返回了一个binder的对象,服务进行的操作,其实就是这个返回对象实现类的操作。一般都服务的功能主要是下载等功能,这里主要对服务的启动形式进行分析,功能方面就不说了。

  • 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/start"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="开启事务"/>

    <Button
        android:id="@+id/stop"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="停止服务" />
</LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/bind"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="绑定事务"/>

        <Button
            android:id="@+id/unbind"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="解除绑定" />
    </LinearLayout>
</LinearLayout>
  • 启动服务
package com.example.myservice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


    private MyService.Mybind mybind;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myService();
    }

    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mybind = (MyService.Mybind) iBinder;
            mybind.start();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    private void myService() {
        Intent intent = new Intent(this,MyService.class);
        Button start = findViewById(R.id.start);
        Button stop = findViewById(R.id.stop);
        Button bind = findViewById(R.id.bind);
        Button unbind = findViewById(R.id.unbind);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startService(intent);
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopService(intent);
            }
        });
        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bindService(intent,sc,BIND_AUTO_CREATE);
            }
        });
        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unbindService(sc);
            }
        });
    }

}

可以看到这种启动形式比上面一种麻烦很多,首先对于服务需要在onbind()中返回一个binder对象。其次bindService(Intent,sc,1)绑定的时候需要传递三个参数,第一个是intent,第二个是获取binder实例的ServiceerConnection对象,通过重写onServiceConnected(ComponentName componentName, IBinder iBinder)方法获取binder中要实现的功能,第三个传递的是一个字符串,BIND_AUTO_CREATE代表绑定后创建服务;

  • 在AndroidManfest.xml中声明
<service android:name=".MyService"/>

2.生命周期

1.startService生命周期

onCreate() → onStartCommand() → onDestory()

onCreate()服务第一创建的时候调用

onStartCommand()每次启动服务的时候调用

onDestory()服务销毁之前调用

2.bindService生命周期

onCreate() →onBind()→ onunbind()→ onDestory()

此时服务生命周期有两种情况:

1.服务通过startService()已经启动,则不会调用onCreate()方法,点击绑定按钮之后调用onBind()方法;

2.服务未启动,点击启动按钮首先会调用oncreate()进行创建,然后通过onbind()进行绑定

注意:对于startService()启动的服务,通过stopService()可以直接关闭服务,调用onDestory()方法;而对于进行了绑定的服务,则需要通过stopService()和unbindService()操作才能停止服务,停止服务,调用onUnbind()和onDestory()方法;

3.两种启动形式的区别

startService()和bindService()区别:

对于startService()这个方法启动服务,活动不能对它进行操作;活动只能知道服务的启动和暂停,对于服务运行的方法很难捕捉到;而对于bindService(),活动可以通过serviceConnection的实体类对onbind()返回的binder实现类实现的功能进行捕捉;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值