利用接口调用服务中特定的方法
利用接口调用服务中特定的方法,好处:是为了保护服务中的其他方法
public interface PayInterface {
public void interface_pay();
}
public class PayService extends Service {
class MyBinder extends Binder implements PayInterface{
@Override
public void interface_pay() {
pay();
}
}
@Override
public IBinder onBind(Intent intent) {
MyBinder binder = new MyBinder();
return binder;
}
@Override
public void onCreate() {
super.onCreate();
}
public void pay(){
System.out.println("支付服务");
}
}
public class MainActivity extends AppCompatActivity {
private Intent intent;
private MyServiceConnection serviceConnection;
private PayInterface payInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this,PayService.class);
serviceConnection = new MyServiceConnection();
}
public void bind(View view){
bindService(intent,serviceConnection,BIND_AUTO_CREATE);
}
public void pay(View view){
if(payInterface!=null){
payInterface.interface_pay();//调用支付功能。
}
}
class MyServiceConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
payInterface = (PayInterface) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
}