Search code examples
javaandroidservicebroadcastreceiveralarmmanager

Android – Trouble with AlarmManager and BroadcastReceiver


In my android application, I am trying to print a message in the log every 5 seconds. I am using a simple configuration with AlarmManager and BroadcastReceiver, which seems to be working for everyone except for me. This is the code for the Broadcast Receiver:

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ServiceAlarmReceiver extends BroadcastReceiver {    

private final String TAG = "com.example.ahsandroidapplication";

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

    Log.i(TAG, "Broadcast received");

}

public void setAlarm(Context context){

    System.out.println("Service started");

    long alertTime = System.currentTimeMillis() + 5000;
    Intent alertIntent = new Intent(context, ServiceAlarmReceiver.class);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, alertTime, PendingIntent.getBroadcast(context, 1, alertIntent, 
            PendingIntent.FLAG_UPDATE_CURRENT));


}
}

The problem is that the broadcast receiver is not detecting any broadcasts. Can anyone tell me what I am doing wrong? Any help is appreciated.

Edit:

After some looking around, I have concluded that I need to declare the receiver in the manifest. If this is the problem, how would I go about doing that?


Solution

  • Okay, so I defined the receiver in my manifest, and now it works fine:

    <receiver android:name=".ServiceAlarmReceiver"
            android:enabled="true">   
      <intent-filter>
         <action android:name="com.example.ahsandroidapplication.mybroadcast"></action>
      </intent-filter>
    

    To the receiver, I added the line:

    alertIntent.setAction("com.example.ahsandroidapplication.mybroadcast");
    

    For experimental purposes, I set it to go off every second, and it is exploding in my log. Now I'll see about trying to cancel it.