public class MainActivity extends AppCompatActivity {

private Myconn conn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//点击按钮 开启服务 通过startservice
public void click1(View v) {
Intent intent = new Intent(this, DemoService.class);
startService(intent); // 开启服务
}
public void click2(View v) {
Intent intent = new Intent(this, DemoService.class);
stopService(intent);
}
//点击按钮 绑定服务 开启服务的第二种方式
public void click3(View v) {
Intent intent = new Intent(this,DemoService.class);
//连接到DemoService这个服务
conn = new Myconn();
bindService(intent, conn, BIND_AUTO_CREATE);
}
//点击按钮手动解绑服务
public void click4(View v) {
unbindService(conn);
}

@Override
protected void onDestroy() {
//当Activity销毁的时候 要解绑服务
unbindService(conn);
super.onDestroy();
}

//定义一个类 用来监视服务的状态
private class Myconn implements ServiceConnection{
//当服务连接成功调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("jojo", "onServiceConnected: ");
}
//失去连接时调用
@Override
public void onServiceDisconnected(ComponentName name) {

}
}
}


public class DemoService extends Service {
private static final String TAG = "jojo";
public DemoService() {
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
Log.d(TAG, "onBind: ");
return null;
}

//当服务第一次创建的时候调用
@Override
public void onCreate() {
Log.d(TAG, "onCreate: ");
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}

//当服务销毁的时候调用
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: ");
super.onDestroy();
}

@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind: ");
return super.onUnbind(intent);
}
}