在开发中,如果想要调用某一个类的部分方法,但是这个类中的方法又不能全部暴露,那该怎么办呢?该类到底要不要使用private修饰?首先我们要明确一件事情,那就是类一定要用private修饰,因为内部的某些功能不能暴露,那该如何调用该类中的某些方法?要解决这个问题其实很简单,那就是让该类实现一个公开接口,在接口中仅仅定义需要实现的方法即可。具体如下所示所示
在下面代码中,如果我们想要调用InnerBinder 类中的callServiceInnerMethod()方法应该如何做?需要注意的是,InnerBinder 使用了private修饰。
package com.example.p5service.service;
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 androidx.annotation.Nullable;
import com.example.p5service.interfaces.ICommunication;
/**
* service生命周期
*/
public class FirstService extends Service {
private static final String TAG = "FirstService";
private class InnerBinder extends Binder implements ICommunication {
public void callServiceInnerMethod(){
sayHello();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new InnerBinder();
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "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() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
private void sayHello(){
Log.d(TAG, "sayHello: Hello");
Toast.makeText(this,"Hello",Toast.LENGTH_SHORT).show();
}
}
代码中可以看出,InnerBinder 实现了ICommunication接口,该接口就是我们使用的中间接口,接口定义如下
package com.example.p5service.interfaces;
public interface ICommunication {
void callServiceInnerMethod();
}
在接口中,仅仅定义了我们需要使用的callServiceInnerMethod()方法,并且该接口是对外公开的,此时我们如果想要使用InnerBinder中的callServiceInnerMethod()的话,仅仅需要定义一个接口的对象,然后通过调用该对象的方法即可,具体代码如下:
package com.example.p5service;
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.example.p5service.interfaces.ICommunication;
import com.example.p5service.service.FirstService;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ICommunication mBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 开启服务
*
* @param view
*/
public void startService(View view) {
Intent intent = new Intent();
intent.setClass(this, FirstService.class);
startService(intent);
}
/**
* 结束服务
*
* @param view
*/
public void stopService(View view) {
Intent intent = new Intent();
intent.setClass(this, FirstService.class);
stopService(intent);
}
public void callServiceMethod(View view) {
Log.d(TAG, "callServiceMethod: ");
mBinder.callServiceInnerMethod();
}