import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ServiceBindActivity extends Activity {
  Button bind;
  Button unbind;
  Button getServiceStatus;
  //保持所启动的Service的IBinder对象
  BindService.MyBinder binder;
  //定义一个ServiceConnection对象
  private ServiceConnection conn = new ServiceConnection() {

    //当该Activity与Service断开连接时回调该方法
    @Override
    public void onServiceDisconnected(ComponentName name) {
      System.out.println("--Service Disconnected--");

    }

    //当该Activity与Service连接成功时回调该方法
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
      System.out.println("--Service Coonnected");
      //获取Service的onBind方法所返回的MyBinder
      binder = (BindService.MyBinder)service;
    }
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_service_bind);
    //获取程序界面中的start、stop、getServiceStatus按钮
    bind = (Button) findViewById(R.id.bind);
    unbind = (Button) findViewById(R.id.unbind);
    getServiceStatus = (Button) findViewById(R.id.getServiceStatus);
    //创建启动Service的Intent
    final Intent intent = new Intent();
    //为Intent设置Action属性
    intent.setAction("mediaprovider.service.BIND_SERVICE");
    bind.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
      // 绑定指定Service
      bindService(intent, conn, Service.BIND_AUTO_CREATE);
    }
  });
  unbind.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
      //解除绑定Service
      unbindService(conn);
    }
  });
  getServiceStatus.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
      // 获取并显示Service的count
      Toast.makeText(ServiceBindActivity.this,
        "Service的count值为:"+binder.getCount(), 4000).show();
    }
  });
}

 

}

posted on 2016-06-21 10:42  奋斗青年一族  阅读(236)  评论(0编辑  收藏  举报