public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btn_start;
private Button btn_stop;
private Intent intent;
private ServiceConnection serviceConnection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start=findViewById(R.id.btn_start);
btn_stop=findViewById(R.id.btn_stop);
//点击事件
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(MainActivity.this, MyService.class);
serviceConnection=new ServiceConnection() {
//和服务建立连接调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "onServiceConnected: ");
MyService.MyBinder binder=(MyService.MyBinder)service;
}
//断开连接调用,非正常断开才调用
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG, "onServiceDisconnected: ");
}
};
//绑定启动
bindService(intent,serviceConnection, Service.BIND_AUTO_CREATE);
// startService(intent);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//解绑
// stopService(intent);
unbindService(serviceConnection);
}
});
}
}
public class MyService extends Service {
private static final String TAG = "MyService";
public MyService() {
}
//生命周期
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ");
}
//稍候->调用服务里面的方法
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented1111111111");
return new MyBinder();
}
public class MyBinder extends Binder{
public void send(){
Log.i(TAG, "send: 123");
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy: ");
}
}
绑定方式:onCreate() – onBind() — onUnbind() — onDestroy()
绑定服务:bindService()
解除绑定:unbindService()
Service生命周期和启动方式
最新推荐文章于 2022-06-05 12:07:32 发布