2015年10月19日 星期一

Service-2-On Bind

Another method a Service is Bind Service(都係不會自已整Thread)

The different between the BindService and the normal Service is user can communicate to the  Service after Bind it.

A service can be start and bind at the same time.If a service be bined, if user call stopService() cannot stop it. Until all the user call unvindService();

1.Create a Servie class

public class MyService extends Service {
    


    public MyService() {
    }

   

   

    

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("ser", "onCreate");
       
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("ser", "onDestroy");
       
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("ser", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.i("ser", "onBind");
        return null;
    }

   
}

2. In the Service call create a innear class MyBinder
MyBinder use to commuincate between the service and the activity.


 class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }

    }

3.in oerder to communicate to the Service, we need to create some Method,here we create the 
getCurrentNum, it can get the increasing number in the services's worker thread.



public class MyService extends Service {
    MyBinder myBinder;
    private Timer timer;
    private TimerTask timerTask;
    private int i = 0;


    public MyService() {
    }

    private  void startTimer() {
        if (timer == null) {
            timer = new Timer();
            timerTask = new TimerTask() {


                @Override
                public void run() {
                    i++;
                    Log.i("time",i+"");

                }
            };
        }

        timer.schedule(timerTask, 0, 1000);//is a new thread
    }

    private  void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timerTask.cancel();
            timer = null;
        }
    }

    public int getCurrentNum() {

        return i;

    }

4. in the call bindservice Activity, we need to get the MyBind object,so we need the activity exthends ServiceConnection and override onServiceConnected  and onServiceDisconnected


public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {

@Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.i("ser", "onServiceConnected");
        MyService.MyBinder binder = (MyService.MyBinder) service;
       myService=binder.getService();

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.i("ser", "onServiceDisconnected");

    }


we can see that after we get the MyBind pbject ,than get the service, we can communicate with the service by getCurrentNum.



The hole code

MainActivity


public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {
    MyService myService;
    Intent intent;
    private Button btStart, btStop, btBind, btunBind,btgetBMI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btStart = (Button) findViewById(R.id.btStartS);
        btStop = (Button) findViewById(R.id.btStopS);
        btBind = (Button) findViewById(R.id.btBinds);
        btunBind = (Button) findViewById(R.id.btUnBind);
        btgetBMI = (Button) findViewById(R.id.btGetBmi);

        btStart.setOnClickListener(this);
        btStop.setOnClickListener(this);
        btBind.setOnClickListener(this);
        btunBind.setOnClickListener(this);
        btgetBMI.setOnClickListener(this);

        intent = new Intent(this, MyService.class);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btStartS:

                startService(intent);
                break;
            case R.id.btStopS:
                stopService(intent);
                break;
            case R.id.btBinds:
                bindService(intent, this, BIND_AUTO_CREATE);
                break;
            case R.id.btUnBind:
                unbindService(this);
                break;
            case R.id.btGetBmi:
               int answer= myService.getCurrentNum();
                Toast.makeText(this,answer+"",Toast.LENGTH_LONG).show();
                break;
        }

    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.i("ser", "onServiceConnected");
        MyService.MyBinder binder = (MyService.MyBinder) service;
       myService=binder.getService();

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.i("ser", "onServiceDisconnected");

    }
}

MyService


public class MyService extends Service {
    MyBinder myBinder;
    private Timer timer;
    private TimerTask timerTask;
    private int i = 0;


    public MyService() {
    }

    private  void startTimer() {
        if (timer == null) {
            timer = new Timer();
            timerTask = new TimerTask() {


                @Override
                public void run() {
                    i++;
                    Log.i("time",i+"");

                }
            };
        }

        timer.schedule(timerTask, 0, 1000);//is a new thread
    }

    private  void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timerTask.cancel();
            timer = null;
        }
    }

    public int getCurrentNum() {

        return i;

    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
        super.dump(fd, writer, args);
        Log.i("ser", "dump");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("ser", "onCreate");
        startTimer();
        myBinder = new MyBinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("ser", "onDestroy");
        stopTimer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("ser", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.i("ser", "onBind");
        return myBinder;
    }

    class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }
}

remark:the timertask will create a worker thraed to calculate