0

I am using broadcast receiver with AlarmManager, but sometimes it takes lot of seconds to wake up, which causes issue in app functionality

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();

and releases after launching activity

I am thinking to change it.

Can you tell what is the best approach?

  1. use broadcast receiver to perform some calculations, and then starts activity (wake lock problem so far in my case).

  2. Start Activity directly, and do calculations weather to continue this activity or terminate before setting content view

Haris
  • 1,822
  • 2
  • 22
  • 44

1 Answers1

0

I am using broadcast receiver with AlarmManager, but sometimes it takes lot of seconds to wake up, which causes issue in app functionality

I am not aware that any other sort of component will somehow start up faster than a BroadcastReceiver. Certainly I would expect an activity to start up more slowly than does a BroadcastReceiver.

and releases after launching activity

The WakeLock is doing you no good, as there already is a WakeLock in place for the duration of your onReceive() call (assuming that this is a manifest-registered BroadcastReceiver).

The only way this WakeLock will be useful is if you release it from onCreate() of the activity, to try to keep the device awake long enough for the activity to start up.

Can you tell what is the best approach?

That depends on what the "calculations" are. onReceive() is called on the main application thread. Like all methods called on the main application thread, you want onReceive() to return in a couple of milliseconds. If your "calculations" will definitely take only a couple of milliseconds, stick with the BroadcastReceiver. If the "calculations" will take longer than that, you will want to consider delegating that work to an IntentService, and have the IntentService start the activity if needed.

With respect to the "lot of seconds", bear in mind that your AlarmManager events may be inexact, depending on what method you use to set them up, what your targetSdkVersion is, and what version of Android you are running on.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491