start开启服务
public class MainActivity extends Activity implements OnClickListener{
private Button button1, button2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
public void onClick(View v) {
Intent service;
switch (v.getId()) {
case R.id.button1://开启服务
service = new Intent(MainActivity.this,MyStartService.class);
startService(service );
break;
case R.id.button2://停止服务
service = new Intent(MainActivity.this,MyStartService.class);
stopService(service);
break;
}
}
}
public class MyStartService extends Service {
public IBinder onBind(Intent intent) {
Log.i("myTag", "onBind--->被调用");
return null;
}
/**
* 创建服务的时候会调用此方法
* */
public void onCreate() {
super.onCreate();
Log.i("myTag", "onCreate--->被调用");
}
/**
* 服务开启的时候会调用此方法
* */
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("myTag", "onStartCommand--->被调用");
return super.onStartCommand(intent, flags, startId);
}
/**
* 服务被销毁的时候会调用此方法
* */
public void onDestroy() {
super.onDestroy();
Log.i("myTag", "onDestroy--->被调用");
}
}