1、创建service类,并在AndroidManifest.xml里面注册该组件。
public class FirstService extends Service{}
<service
android:name=".FirstService"
android:enabled="true"
android:exported="true"></service>
2、在service类中重写一些方法
启动和关闭service有两组方法可以被使用:
(1)startService和stopService
//Service被绑定时回调该方法(虽然在startService和stopService这组方法下onBind()没用,但必须写,不然会报错)
@Override
public IBinder onBind(Intent intent) {
System.out.println("Service is bind");
return null;
}
//Service被创建时回调该方法
@Override
public void onCreate() {
super.onCreate();
System.out.println("Service is Created");
}
//Service被启动时回调该方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("Service is Started");
return super.onStartCommand(intent, flags, startId);
}
//Service被关之前回调该方法
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("Service is Destroyed");
}
(2)bindService和unbindService
//Service被创建时回调该方法
@Override
public void onCreate() {
super.onCreate();
System.out.println("Service is Created");
}
//Service被绑定时回调该方法
@Override
public IBinder onBind(Intent intent) {
System.out.println("Service is bind");
return null;
}
//Service被解除绑定时回调该方法
@Override
public boolean onUnbind(Intent intent) {
System.out.println("Service is unbind");
return super.onUnbind(intent);
}
//Service被关之前回调该方法
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("Service is Destroyed");
}
3、MainActivity中启动、关闭Service
(在布局文件中设置按钮控制service的启动和关闭)
启动和关闭service有两组方法可以被使用:
(1)startService和stopService
Button stopBn = findViewById(R.id.stopBn);
Button bindBn = findViewById(R.id.bindBn);
startBn.setOnClickListener(v -> startService(new Intent(this,FirstService.class)));
stopBn.setOnClickListener(v -> stopService(new Intent(this,FirstService.class)));
(2)bindService和unbindService
Button bindBn = findViewById(R.id.bindBn);
Button unbindBn = findViewById(R.id.unbindBn);
bindBn.setOnClickListener(v -> bindService(new Intent(this,FirstService.class),connection,Context.BIND_AUTO_CREATE));
unbindBn.setOnClickListener(v -> unbindService(connection));
//activity和service的桥梁
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};