I am new to android. I was playing with the AlarmManager and had successufully go a piece of code running with the BroadcastReceiver as a separate class.
I am now trying to put the BroadcastReceiver as inner class but have no luck on firing the BroadcastReceiver. I had no idea what might have gone wrong after hours looking at the code...
Here is my code:
public class InnerService extends Service{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(InnerBroadcastReceiver.class.toString());
Log.d("InnerService","InnerService starts!");
Log.d("InnerService","class : "+InnerBroadcastReceiver.class.toString());
this.registerReceiver(new InnerBroadcastReceiver(), filter);
scheduleTestAlarmReceiver(this);
}
public static void scheduleTestAlarmReceiver(Context context) {
Log.d("scheduleTestAlarmReceiver", "scheduleTestAlarmReceiver start");
Intent receiverIntent = new Intent(context, InnerBroadcastReceiver.class);
receiverIntent.setAction("com.example.alarmmanagertest.InnerService$InnerBroadcastReceiver");
PendingIntent sender = PendingIntent.getBroadcast(context, 123456789,
receiverIntent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 1000, sender);
Log.d("scheduleTestAlarmReceiver", "scheduleTestAlarmReceiver complete");
}
private class InnerBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d("InnerBroadcastReceiver","InnerBroadcastReceiver ALARM Manager fires success!");
}
}
}
It looks like the AlarmManager tried to fire the BroadcastReceiver every second but failed
Logcat:
V/AlarmManager(2439): waitForAlarm result :4
V/AlarmManager(2439): trigger ELAPSED_REALTIME_WAKEUP or RTC_WAKEUP
UPDATE
I have tried to change the code for creating intent in onCreate()
and scheduleTestAlarmReceiver()
to intent = new intent("action_string")
and it works. It seems that intent.setAction()
is not working.
What will be the pros and cons for creating intent with and without context (Intent(Context packageContext, Class<?> cls)
and Intent(String action)
)?
But I would still like to know why the above code failed. Can anyone explain?