一、概述:
这里使用简单的除法运算来演示
1、创建FirstActivity
public class FirstActivity extends AppCompatActivity implements CacuService.OnCacuListener {
private static final String TAG = FirstActivity.class.getSimpleName() ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_down);
ButterKnife.inject(this);
}
@OnClick(R.id.btn_cacu)
public void cacu(View view){
new CacuService().divide(3,4,this);
}
@Override
public void onError(String str) {
Log.i("tag", str);
}
@Override
public void onSuccess(float result) {
Log.i("tag", result + "");
}
}
2、创建控制层CacuService
public class CacuService {
public interface OnCacuListener{
void onError(String str);
void onSuccess(float result);
}
public void divide(int a, int b, OnCacuListener listener){
new Thread(new Runnable() {
@Override
public void run() {
try {
SystemClock.sleep(2000);
float result = a / b;
if (listener != null){
listener.onSuccess(result);
}
} catch (Exception e) {
//e.printStackTrace();
if (listener != null){
listener.onError(e.getMessage());
}
}
}
}).start();
}
}