1.MainActivity
//声明中间人
private BindService.IBind iBind;
Intent service=new Intent(MainActivity.this,BindService.class);
ServiceConnection conn=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//得到中间人
iBind= (BindService.IBind) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
//绑定服务
bindService(service,conn,BIND_AUTO_CREATE);
//通过中间人调用服务中获取随机数的方法
int num = iBind.getNum()
2.创建service类继承service
package com.example.renzhili20181205.service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import java.util.Random;
public class BindService extends Service {
private IBind iBind=new IBind();
@Override
public IBinder onBind(Intent intent) {
return iBind;
}
//定义中间人
public class IBind extends Binder{
//获取随机数的方法
public int getNum(){
return new Random().nextInt(999999);
}
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
}