Android--Service②-->接口重构来服务调用服务内部的方法

本文介绍如何通过接口重构提高Android Service的封装性,详细讲解了创建接口、服务中实现IBinder子类以及在活动中接收服务返回的IBinder对象的步骤,强调了隐藏内部实现、只暴露接口的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

上篇博客中我们解决了怎么启动,关闭服务,怎么调用服务内部的方法,这篇博客我们就来讨论一下怎么用接口来让服务内部的实现更加的隐蔽,值暴露接口


提示:以下是本篇文章正文内容,下面案例可供参考

一、使用步骤

1.创建接口

public interface ICommunication {
    void callServiceMethod();
}

2.在服务中定义一个实现了接口的IBinder的子类,并在onBind中返回

    private class InnerBinder extends Binder implements ICommunication {
        @Override
        public void callServiceMethod() {
            sayHello();
        }
    }
    /*
    调用bindService时使用
     */
    @Override
    public IBinder onBind(Intent intent) {
        return new InnerBinder();
    }

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

3.在活动中定义一个接口去接受服务返回的IBinder对象

private ICommunication binder;
    private final ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder= (ICommunication) service;
            Log.i("TAG", "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("TAG", "onServiceDisconnected");
            binder = null;
        }
    };

二、使用接口的优势

1.隐藏内部实现的细节,暴露接口

三、完整代码

xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent"
    tools:context=".activity.FirstTestActivity">
    <TextView
        style="@style/style_tv"
        android:layout_marginTop="0dp"
        android:onClick="bindServiceClick"
        android:text="@string/bind_service"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        style="@style/style_tv"
        android:layout_marginTop="45dp"
        android:onClick="unbindServiceClick"
        android:text="@string/unbind_service"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        style="@style/style_tv"
        android:layout_marginTop="90dp"
        android:onClick="callServiceMethod"
        android:text="@string/call_service_method"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

接口:

public interface ICommunication {
    void callServiceMethod();
}

服务类:

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

import com.lbj23.testservice.interfaces.ICommunication;

public class MySecondService extends Service {
    /*
    打Log时的TAG
     */
    private final static String TAG = "TAG";
    /*
    构造方法
     */
    public MySecondService() {
    }
    /*
    自定义一个InnerBinder继承自Binder,实现ICommunication接口
     */
    private class InnerBinder extends Binder implements ICommunication {
        @Override
        public void callServiceMethod() {
            sayHello();
        }
    }
    /*
    调用bindService时使用
     */
    @Override
    public IBinder onBind(Intent intent) {
        return new InnerBinder();
    }

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

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

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

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

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, "onRebind");
        super.onRebind(intent);
    }

    private void sayHello() {
        Toast.makeText(this, "Hi !!!", Toast.LENGTH_SHORT).show();
    }
}

活动:

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.util.Log;
import android.view.View;

import com.lbj23.testservice.R;
import com.lbj23.testservice.interfaces.ICommunication;
import com.lbj23.testservice.service.MyFirstService;
import com.lbj23.testservice.service.MySecondService;

public class SecondTestActivity extends AppCompatActivity {


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

    public void callServiceMethod(View view) {
        if (binder != null) {
            binder.callServiceMethod();
        }
    }
    private ICommunication binder;
    private final ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder= (ICommunication) service;
            Log.i("TAG", "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("TAG", "onServiceDisconnected");
            binder = null;
        }
    };

    public void unbindServiceClick(View view) {
        if (serviceConnection != null) {
            unbindService(serviceConnection);
        }
    }

    public void bindServiceClick(View view) {
        bindService(new Intent(this, MySecondService.class), serviceConnection, BIND_AUTO_CREATE);
    }
}

四、项目压缩包

点击下载

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值