Klipnov
Klipnov

Reputation: 105

Android Notifications by Service

I have been trying to develop this features for days and just keep getting errors and bugs. I am making an app that will notify users when it's time to pray. I have all the prayer times inside a db downloaded from a server in json format. The data is all correct as I have checked multiple times.

I have created a Service that will set Alarm using AlarmManager. Then I bind my MainActivity to the Service. From the main activity I set Alarm using a method from the service called setAlarmAccordingToDB(). The problem is when I bind my service. The service gets destroyed when app is closed. Upcoming notifications are not notified.

Then I tried to start the service and bind it to my activity.Called setAlarmAccordingToDB(). What happened was setAlarmAccordingToDB was called repeatedly. It kept setting up new alarms non-stop.

Any advice on how upcoming notifications should be set?

Upvotes: 0

Views: 249

Answers (2)

Klipnov
Klipnov

Reputation: 105

I tried to use a separate class for broadcastReceiver and it seems to work. I just used Alarm Manager and BroadcastReceiver. After the revised code, my app could fire the notifications even when the phone screen is turned off and app closed.

Before this i used:-

        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

               displayNotification();

            }
        };

Now, I created a class:-

public class Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        NotificationManager notificationManager;
        notificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
        displayNotification(context);

    }
}

In the AndroidManifest.xml I added

<receiver android:name=".Receiver" android:process=":remote"></receiver>

Upvotes: 0

Booger
Booger

Reputation: 18725

You probably need to use a Wakeful service, so the device/process wakes up when the alarm is called.

I have used this code for a while in my app (not the project, just modified my code from Mark's examples) with great results.

https://github.com/commonsguy/cwac-wakeful

Upvotes: 1

Related Questions