To run any code in the background you need to create a service class, when your app goes into background start that service using "startService()" method, but you need also to create a notification telling the user that the app is running a service so the system will not kill your service. this is the notification :
Notification.Builder builder = new Notification.Builder(this)
.setContentTitle("Title")
.setContentText("content");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
builder.setChannelId(channelId)
//Make this notification ongoing so it can’t be dismissed by the user//
.setOngoing(true)
.setSmallIcon(R.drawable.notification_icon);
startForeground(id, builder.build());
and inside the service class's onCreate write your logic. hope this helps