zoukankan      html  css  js  c++  java
  • 利用接口调用服务中特定的方法

    利用接口调用服务中特定的方法,好处:是为了保护服务中的其他方法

    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);
        }
    }

     

  • 相关阅读:
    PAT 1018. 锤子剪刀布
    PAT 1017. A除以B
    PAT 1016. 部分A+B
    PAT 1015. 德才论
    PAT 1014. 福尔摩斯的约会
    PAT 1013. 数素数
    PAT 1012. 数字分类
    PAT 1011. A+B和C
    292. Nim Game
    412. Fizz Buzz
  • 原文地址:https://www.cnblogs.com/anni-qianqian/p/5402442.html
Copyright © 2011-2022 走看看