Android中Service(后台服务)详解

  package com.example.servicetest;

  import com.example.servicetest.service.MyService;

  import android.app.Activity;

  import android.content.ComponentName;

  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.view.View.OnClickListener;

  import android.widget.Button;

  public class MainActivity extends Activity implements OnClickListener {

  /** 标志位 */

  private static String TAG = "com.example.servicetest.MainActivity";

  /** 启动服务 */

  private Button mBtnStart;

  /** 绑定服务 */

  private Button mBtnBind;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  initView();

  }

  /**

  * init the View

  */

  private void initView() {

  mBtnStart = (Button) findViewById(R.id.startservice);

  mBtnBind = (Button) findViewById(R.id.bindservice);

  mBtnStart.setOnClickListener(this);

  mBtnBind.setOnClickListener(this);

  }

  @Override

  public void onClick(View view) {

  switch (view.getId()) {

  // 启动服务的方式

  case R.id.startservice:

  startService(new Intent(MyService.ACTION));

  break;

  // 绑定服务的方式

  case R.id.bindservice:

  bindService(new Intent(MyService.ACTION), conn, BIND_AUTO_CREATE);

  break;

  default:

  break;

  }

  }

  ServiceConnection conn = new ServiceConnection() {

  public void onServiceConnected(ComponentName name, IBinder service) {

  Log.v(TAG, "onServiceConnected");

  }

  public void onServiceDisconnected(ComponentName name) {

  Log.v(TAG, "onServiceDisconnected");

  }

  };

  @Override

  protected void onDestroy() {

  super.onDestroy();

  System.out.println("-------onDestroy()--");

  stopService(new Intent(MyService.ACTION));

  unbindService(conn);

  }

  }