javaandroidandroid-intentlocalbroadcastmanager

Local Broadcast Manager using an alarm not received by main Activity


I have implemented an alarm manager it is working pretty well and every 15 minutes it is triggered. Now I want to call a MainActivity method every 15 minutes using the alarm. So I use a Local Broadcaster to the MainActivity (knowing that this is the current activity running on my phone) to transmit the order to start the method. But the problem is that the MainActivity is not receiving the data on the onReceive method.

Alarm

@Override
public void onReceive(Context context, Intent intent) {
    cont = context;
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
    wl.acquire();


    String url = intent.getExtras().getString("url");
    Log.w(TAG, "Service " + url);

    new GetJSON_val(){
        @Override
        protected String[] doInBackground(String... url) {
            Some Code...

        @Override
        protected void onPostExecute(String[] result) {
            Some Code...

            // I send the broadcast to main Activity
            Log.e("sender", "Broadcasting message");
            Intent intent = new Intent("custom-event-name");

            intent.putExtra("message", "This is my message!");

            LocalBroadcastManager.getInstance(cont).sendBroadcast(intent);

                }
            }
        }
    }.execute(url);


    // End of alarm code

    wl.release();
}

Main Activity

  @Override
  public void onCreate(Bundle savedInstanceState) {
  ...
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
            new IntentFilter("custom-event-name"));
   ...
}
   private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("message");
        Log.e("receiver", "Got message: " + message);

    }
};

The Local Broadcaster is created in the Alarm class in postExecute method.


Solution

  • I think the problem is you are performing long running task in onReceive() and accessing same context

    you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed).

    Solution

    1. Either you use goAsync() .

    2. Or use a IntentService for background task and sendBroadcast after task is completed .