Search code examples
androidandroid-activitybroadcastreceiveralarmmanagerbackground-process

AlarmManager keeps bringing activity to foreground


I'm trying to write code that will run in the background and call server APIs. Googling led me to use AlarmManager, here is my code:

            AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            int interval = 4000;

            Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);

            manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

The problem here though, is when my app is on the foreground (currently in android main menu, or on another app), whenever the alarm fires, it sends my activity to the front.

Anyone know why this happens and how I can avoid this? I have a service that is started by the AlarmReceiver class, and I want it to run on the background.

AlarmReceiver.class:

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Intent i = new Intent(context, LogService.class);
    i.putExtra("param1", "index.html");
    i.putExtra("param2",
        "http://www.vogella.com/index.html");
    context.startService(i);
}

}

LogService.class

public class LogService extends IntentService{

    public LogService() {
        super("LogService");
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String param1 = intent.getStringExtra("param1");
        String param2 = intent.getStringExtra("param2");

        Log.i("Hello from logservice!", "!!! -- " + param1 + " - " + param2);
    }

}

Added stuff to manifest:

<receiver android:name="com.example.app.alarm.AlarmReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

<service android:name="com.example.app.alarm.LogService" >
</service>

Thanks in advance!


Solution

  • After reading around, I've found out that since API 19, all repeating alarms are inexact. After knowing about this, I tried using the setRepeating function. I don't know why it behaves differently, but all is working as intended now.