| 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); } } |