Android 通过接口的方式去调用服务里面的方法

时间:2024-01-01 09:10:09
public class MainActivity extends AppCompatActivity {
private MyConn conn;
private Iservice myBinder; // 我定义的中间人对象 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); Intent intent = new Intent(this, DemoService.class);
//连接服务
conn = new MyConn();
bindService(intent, conn, BIND_AUTO_CREATE);
} //点击按钮调用服务里面banzheng的方法
public void click(View v) {
myBinder.callBanZheng();
} //监视服务的状态
private class MyConn implements ServiceConnection{
//当服务连接成功调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//获取中间人对象
myBinder = (Iservice) service;
}
//失去连接
@Override
public void onServiceDisconnected(ComponentName name) { }
} @Override
protected void onDestroy() {
//当Activity销毁的时候 解绑服务
unbindService(conn);
super.onDestroy();
}
}
public class DemoService extends Service {
private static final String TAG = "jojp";
public DemoService() {
}
// 把我定义的中间人对象返回
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return new MyBinder();
} //banzheng的方法
public void banZheng(int money) {
if (money > ) {
Toast.makeText(getApplicationContext(), "banZheng", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "banZhengFail", Toast.LENGTH_SHORT).show();
}
} //打麻将的方法
public void playMaJiang() {
Log.d(TAG, "playMaJiang: ");
}
//洗桑拿的方法
public void sangNa() {
Log.d(TAG, "sangNa: ");
} private class MyBinder extends Binder implements Iservice{
@Override
public void callBanZheng(int money) {
//调用banzheng的方法
banZheng(money);
}
public void callPlayMaJiang() {
//调用playMaJiang的方法
playMaJiang();
}
public void callSangNa() {
//调用洗桑拿的方法
sangNa();
}
}
}
public interface Iservice {
//把领导想暴露的方法都定义在接口里
public void callBanZheng(int money);
}