Android中Activity和Service的绑定(二)

public class BinderActivity extends Activity {



    private Button startBinderServices;

    private Button stopBinderServices;

    private Boolean isConnected = false;



    protected void onCreate(Bundle savedInstanceState) {

        

        super.onCreate(savedInstanceState);

        setContentView(R.layout.binder);

        startBinderServices = (Button) findViewById(R.id.btnstartBinderServices);

        stopBinderServices = (Button) findViewById(R.id.btnstopBinderServices);

        startBinderServices.setOnClickListener(listener);

        stopBinderServices.setOnClickListener(listener);

    }



    private OnClickListener listener = new OnClickListener() {



        public void onClick(View v) {

            

            switch (v.getId()) {

            case R.id.btnstartBinderServices:

                bindService();

                break;



            case R.id.btnstopBinderServices:

                unbind();

                break; 



            default:

                break;

            }

        }

    };



    private void unbind() {



        if (isConnected) {



            unbindService(conn);

            isConnected = false;

        }

    } 



    private void bindService() {



        Intent intent = new Intent(BinderActivity.this, BindService.class);

        bindService(intent, conn, Context.BIND_AUTO_CREATE);

    }

    

    private ServiceConnection conn = new ServiceConnection() {

        

        public void onServiceDisconnected(ComponentName name) {

            

            isConnected = false;

        }

        

        public void onServiceConnected(ComponentName name, IBinder binder) {



            MyBinder myBinder = (MyBinder)binder;

            BindService service = myBinder.getService();

            isConnected = true;

            service.MyMethod();

        }

    };



}

 

你可能感兴趣的:(Activity)