android 中activity调用本地service中的方法。

论坛 期权论坛 脚本     
匿名技术用户   2021-1-2 03:21   11   0

1.自定义一个接口,暴露服务中的方法

public interface IService {
/**服务中对外暴露的方法 */
void methodInService();
}

2.自定一个服务类,继承service类

3.在服务类中新建内部类,继承Binder,实现自定义的接口,并在onBind()方法中返回内部类的实例

public class MyService extends Service {

@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}

public class MyBinder extends Binder implements IService{

@Override
public void methodInService() {
serviceMethod1();
}
}

public void serviceMethod1(){
System.out.println("serviceMethod1");
}
}

4.在清单文件中注册服务

<service android:name="com.example.nativeservicemethod.MyService"></service></application>

5.在activity中新建内部类,实现ServiceConnection,然后在onServiceConnected() 方法中强制转化接口实例。

private class MyServiceConnection implements ServiceConnection {

@Override
public void onServiceDisconnected(ComponentName name) {
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iService = (IService) service;
}
};

6.用bind绑定服务,用接口实例调用服务中暴露的方法。

  if (conn == null) {
conn = new MyServiceConnection();
bindService(new Intent(MainActivity.this, MyService.class), conn, Context.BIND_AUTO_CREATE);
}

转载于:https://www.cnblogs.com/Westfalen/p/4419823.html

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP