'Service stope after few Hours in android

I am creating one foreground service and start this service using STICKY. It detect phone lock and on event. It working fine for few hours but after some time that service stops Below is my code

public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand called");
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Service is Running")
            .setContentText("For Screen Off/On events")
            .setSmallIcon(R.drawable.ic_wallpaper_black_24dp)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setColor(getResources().getColor(R.color.colorPrimary))
            .build();
    
    startForeground(1, notification);
    return START_STICKY;
}

private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String appName = getString(R.string.app_name);
        NotificationChannel serviceChannel = new NotificationChannel(
                CHANNEL_ID,
                appName,
                NotificationManager.IMPORTANCE_DEFAULT
        );
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(serviceChannel);
    }
}

Please help me on this



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source