Background service is freezing/lagging android app

Viewed 173

I have been developing an android application in which there is a service and I want to run it for ever.

I am using a broadcast receiver to get screen on-off intents inside oncreate of service and using an alarm manager which starts the service itself after every 25 seconds inside onstartcommand and also performing my other operations in onstartcommand. I have put all the code in onstartcommand inside an thread. But the problem is once the service in running for some hours in background and I reopen the app the app starts lagging and becomes very slow. Before starting the service the app works very fine.

The Brief of my code is as follows -

public class MyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    AlarmManager alarmManagerMain;
    BroadcastReceiver receiver;
    Thread t;
    Thread thread;

        @Override
    public void onCreate()  {
        super.onCreate();
        t = new Thread(() -> {
            HandleReceiver();
        });
        t.start();
        CreateNotificationChannel();
        startNotification();
    }

    private void HandleReceiver() {
        try {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Intent.ACTION_SCREEN_ON);
            intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
            receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if(intent.getAction().equals(Intent.ACTION_SCREEN_ON))
                    {
                        // ...
                        // My Code
                        // ...
                        // Starting Service to call onStartCommand
                        Intent serviceIntent = new Intent(context, MyService.class);
                        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                        {
                            startForegroundService(serviceIntent);
                        }
                        else
                        {
                            startService(serviceIntent);
                        }
                    }
                    else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
                    {
                        // ...
                        // My Code
                        // ...
                    }
                }
            };
            MyService.this.registerReceiver(receiver, intentFilter);
        }
        catch (Exception ignore) { }
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        Runnable runnable = () -> {
            if(allowNotificationAndAlerts)
            {
                // My Code
            }
            // This function is to start the service even after the system kills it
            startAlarm();
        };
        thread = new Thread(runnable);
        thread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    private void startAlarm()
    {
        AlarmManager alarmManager = (AlarmManager) MyService.this.getSystemService(Service.ALARM_SERVICE);
        Intent myIntent = new Intent(MyService.this, MyBroadCastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MyService.this, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 25);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }
    }

    @Override
    public void onDestroy() {
        stopForeground(false);
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}

My questions are -

  1. How can I optimize the service as to run it for ever in background without causing the lag in app
  2. Is there any way to get screen on off intents by system or anything else instead of running the service with broadcast receiver
1 Answers

I got the answer I was able to solve it by removing "android:process=:remote" line from service in manifest and changing shared preferences to database the issue was maybe because shared preferences are not process safe

Related