Android入门之bindService的用法详解

  package org.mk.android.demo;

  import androidx.appcompat.app.AppCompatActivity;

  import android.app.Service;

  import android.content.ComponentName;

  import android.content.Context;

  import android.content.Intent;

  import android.content.ServiceConnection;

  import android.os.Bundle;

  import android.os.IBinder;

  import android.util.Log;

  import android.view.View;

  import android.widget.Button;

  import android.widget.Toast;

  public class MainActivity extends AppCompatActivity {

  private final String TAG = "SimpleBindService";

  private Button buttonBindService;

  private Button buttonStopBinding;

  private Button buttonGetValueFromBinder;

  private Context ctx;

  private Intent intent;

  private SampleBindService.CountNumBinder countNumBinder;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  buttonBindService = (Button) findViewById(R.id.buttonBindService);

  buttonStopBinding = (Button) findViewById(R.id.buttonStopBinding);

  buttonGetValueFromBinder = (Button) findViewById(R.id.buttonGetValueFromBinder);

  ctx = MainActivity.this;

  intent = new Intent(ctx, SampleBindService.class);

  buttonBindService.setOnClickListener(new OnClickListener());

  buttonStopBinding.setOnClickListener(new OnClickListener());

  buttonGetValueFromBinder.setOnClickListener(new OnClickListener());

  }

  private ServiceConnection conn = new ServiceConnection() {

  //Activity与Service断开连接时回调该方法

  @Override

  public void onServiceDisconnected(ComponentName name) {

  Log.i(TAG, ">>>>>>Service DisConnected");

  }

  //Activity与Service连接成功时回调该方法

  @Override

  public void onServiceConnected(ComponentName name, IBinder service) {

  Log.i(TAG, ">>>>>>Service Connected");

  countNumBinder = (SampleBindService.CountNumBinder) service;

  }

  };

  class OnClickListener implements View.OnClickListener {

  @Override

  public void onClick(View view) {

  Intent eIntent;

  switch (view.getId()) {

  case R.id.buttonBindService:

  bindService(intent, conn, Service.BIND_AUTO_CREATE);

  break;

  case R.id.buttonStopBinding:

  unbindService(conn);

  break;

  case R.id.buttonGetValueFromBinder:

  Toast.makeText(getApplicationContext(), "Service的count" + "的值为:" + countNumBinder.getCount(), Toast.LENGTH_LONG).show();

  break;

  }

  }

  }

  }