Running a foreground service should help you.
Here is a sample foreground service class:
public class YourService extends Service {
public static final String CHANNEL_ID = "YourForegroundServiceChannel";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Your service name")
.setContentText("Your service info")
.setSmallIcon(R.drawable.ic_yours)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
private void createNotificationChannel() {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Your Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
Declare your service in AndroidManifest.xml
:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application ...>
<service
android:name=".service.YourService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
Then start the service as follows:
public void startForegroundService() {
Intent serviceIntent = new Intent(this.getActivity(), YourService.class);
ContextCompat.startForegroundService(this.getActivity(), serviceIntent);
}
For more infos:
https://developer.android.com/guide/components/foreground-services