Infinite loop in android background service, battery drain issues?

820 views Asked by At

I'm writing an app that, among other things, will notify via notification pepople who everyday commute, if the public transport they usually take have some kind of delay.

I considered implement this function using the AlarmManager, but I found too many problems related to how many public transport are chosen and what days the user decides to receive the notifications.

So I came up with another solution: save the user preference into a file, and launch a background service that checks that file every 5 minutes, and if the conditions are respected, it shows the notification:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    while(true){
        try{              
            if (fileCheck()){
                Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.avanti).setContentTitle(getString(R.string.app_name)).setSound(alarmSound);
                mBuilder.setContentText("Test");
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(0, mBuilder.build());
                Thread.sleep(300000)
            }
        } catch (Exception ignored){}
    }
}

And it works, but I have a doubt: is this going to cause performance or battery drain issues? Or is it safe since it sleeps most of the time?

0

There are 0 answers