Search code examples
javaandroidnotificationsbackgroundbroadcastreceiver

How to display a notification when my application is in background?


​I am trying to build an Android application that has -

a First Activity (Launcher activity)

and a Second Activity

What I am trying to achieve :

First Actvity takes an input from user , fetches data from web using an AsyncTaskLoader . In the onLoadFinished it checks if input is valid and if it is starts an Intent to Second Activity to sh​​ow more details . The input is also passed along with the Intent .

Since the network operation can take time so I decided to show a notification using IntentService just before Second Activity is created i.e. the notification is being called in onLoadFinished just before the Intent . The notification should directly start the Second Activity if it isn't already started .

What is working fine :

Both activities and the loader are working fine . The notification is also being displayed and everything is working as expected provided user keeps the app running .

What isn't :

When the user navigates away from First Activity while data is being loaded the notification is not shown because onPause is executed . I tried searching for it and got to know about BroadcastReceiver , JobScheduler and FirebaseJobDispatcher but I can't really understand them and how they help .

So , am I on the right track ? And how can I achieve the same functionality even if app goes into background ?

P.S. The code is much more vast than the problem suggests so I didn't include it . That's why if explanation seems incomplete or messy I will try my best to clarify your doubts .


Solution

  • I finally made it work without using a BroadcastReciever or Service so those of you who are unfamiliar with them can take reference from this but use it your it at your own discretion as Services and Recivers are the recommended way to do it .

    @Override
    public void deliverResult(Data data) {
        super.deliverResult(data);
        showNotification(input);
    }
    

    This is a method in AsyncTaskLoader which is triggered after data is obtained . Override it and alter the method of your notification that responds to notification click .

    private PendingIntent onClick(Context context) {
         return PendingIntent.getActivity(context, 0, new Intent(context, ExtraActivity.class).
    putExtra(Intent.EXTRA_TEXT,input),PendingIntent.FLAG_UPDATE_CURRENT);
    }
    

    The ExtraActivity is similar to this . It allows your notification to respond even if activity has been closed but the notification hasn't .

    Again this is only a workaround for this specific situation which leads to me to pass around the input variable in many places and so it may not be as efficient performance-wise as other options .