1.bindService 监听 回调接口
ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder iBinder) { SpeedTestService.MyBinder binder = (SpeedTestService.MyBinder) iBinder; SpeedTestService service = binder.getService(); service.setCallback(new SpeedTestService.Callback() { @Override public void setResult(String mDownloadSpeed, String mUploadSpeed) { downloadSpeed = mDownloadSpeed; uploadSpeed = mUploadSpeed; } }); } @Override public void onServiceDisconnected(ComponentName name) { } };
Intent intent = new Intent(getContext(), SpeedTestService.class); getContext().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
2.service里定义回调接口
定义回调接口 public interface Callback{ void setResult(String downloadSpeed,String uploadSpeed); } public void setCallback(Callback callback) { mCallback = callback; }
public Callback mCallback; public class MyBinder extends Binder{ public SpeedTestService getService(){ return SpeedTestService.this; } }
使用回调接口
mCallback.setResult(String.valueOf(downloadSpeed),String.valueOf(uploadSpeed));