package com.example.myapp4; import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
/**
* Android 记录Service的生命周期(配置文件中需要引入Service类名)
* @author shaobn
*
*/
public class MainActivity extends ActionBarActivity {
private Button startButton;
private Button stopButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button) this.findViewById(R.id.button1);
stopButton = (Button) this.findViewById(R.id.button2);
startButton.setOnClickListener(new MyClick());
stopButton.setOnClickListener(new MyClick());
}
public class MyClick implements View.OnClickListener{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.button1:
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
break; case R.id.button2:
Intent intent2 = new Intent(MainActivity.this,MyService.class);
stopService(intent2);
break;
}
} }
}
package com.example.myapp4; import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyService extends Service {
@Override
public void onCreate() {
// TODO Auto-generated method stub
System.out.println("--create");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("--onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("--onDestroy");
super.onDestroy();
} }