4

I want to use AlarmManager to schedule a repeating task. Basically, I have this code:

Intent intent = new Intent(INTENT_ACTION_TICK);
// The following line prevents the broadcast receiver from being notified:
intent.setClass(context, MyScheduler.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, intervalInMs, intervalInMs, pendingIntent);

I register MyScheduler as a broadcast receiver in its constructor:

context.registerReceiver(this, new IntentFilter(INTENT_ACTION_TICK));

Everything works as expected (receiver is triggered) unless I add the intent.setClass. Fine with me, however, I distinctly remember reading that you should use explicit intents (intent.setClass) for security reasons.

Is this something I have to consider for my use case?

Zackline
  • 804
  • 1
  • 9
  • 28
  • @Christine It is working if I don't specify the class and just use the action. Only once I specify the class, the class no longer receives the broadcast. I updated the question to make that more clear. – Zackline Nov 18 '16 at 21:46
  • According to the docs, Context.registerReceiver "cannot be called from a BroadcastReceiver component; that is, from a BroadcastReceiver that is declared in an application's manifest." Even though it's working without the setClass(...) call, does that apply to MyScheduler? – Edmund Johnson Nov 18 '16 at 22:01
  • @EdmundJohnson No, it is not declared in the manifest, the intent filter is just programmatically added in the constructor of MyScheduler (which extends BroadcastReceiver). – Zackline Nov 18 '16 at 22:08
  • Did you get this somehow working? I have this problem - intent without a class works, but the app is refused in the Play Store due to security issues. When I add a class, the code stops working (the alarm is not triggered). – Lukas K Apr 15 '23 at 19:33

0 Answers0