Search code examples
androidservicealarmmanagerandroid-pendingintent

Pending intent with Alarm not working in background service


I have several pending intents that I'd like to create when broadcast reciever Boot action runs. Each intent sets off an alarm at a given time. I was able to do this in an activity, however it is not working in a service.

It is strange because logcat shows the data is processing into the for loop and functions, but the alarm does not go off when the time is met.

Can you look over my code and let me know what I am missing?

public class AlarmsService extends Service {

    DatabaseSqlite db = new DatabaseSqlite(this);
    List<Alerts> listAlerts;

    PendingIntent sender;
    Intent intent;
    AlarmManager am;
    int id;
    private int intHour=0;
    private int intMin=0;
    private int intDay=0;
    private int intMonth=0;
    private int intYear=0;

    String alertInMills;
    String alertDuration;
    String eventName ;
    int eventState;

    private String sAlertInMillis;

    String tag = "alerttService";

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Created from Alerts service ...",
                Toast.LENGTH_LONG).show();
        Log.i(tag, "Service created...");


    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "started onstart command Created from Alerts service .");
        return super.onStartCommand(intent, flags, startId);// START_STICKY;
    }

    @Override
    public void onStart(final Intent intent, int startId) {
        super.onStart(intent, startId);

        Toast.makeText(this, "Created service started...",
                Toast.LENGTH_LONG).show();
        Log.i(tag, "Service started...");


        Thread thread = new Thread() {


            public void run() {
                System.out.println("SERVICE -----start thread");
                Boolean x = true;
                while (x) {

                    db.open();
                    listAlerts = db.getAlertsforService();
                    db.close();
                    int alerts=listAlerts.size();


                    for (int i = 0; i < alerts; i++) {
                        Alerts item = listAlerts.get(i);

                     id =item.getRowId();                   
                     alertInMills = item.getAlertTime();
                     alertDuration = item.getAlertMinutes();
                     eventName = item.getEventName();
                     eventState=item.getEventState();

                     System.out.println("SERVICE ----eventName from service "+ eventName);
                     System.out.println("SERVICE ----id from service "+ id);
                     System.out.println("SERVICE ----alertDuration from service "+ alertDuration);
                     System.out.println("SERVICE ----alert UTC Time from alertInMills "+ alertInMills);
                     System.out.println("SERVICE ---- eventState from service "+  eventState);


                    resetAlarm(alertInMills,alertDuration);

                    }


                    x = false;

                }

            }
        };

        thread.start();

    }



    public void resetAlarm(String getAlertInMillisFromDB,
            String getAlertInMinutesFromDB) {


        // extract the military time from the UTC format
        String alertsMilitaryTime = formatUpdateAlertToMilitaryTime(getAlertInMillisFromDB);

        // find the hour and minute
        updateAlertHourAndMinute(alertsMilitaryTime);

        // extract date from the UTC format
        formatUpdateAlertYearMonthDay(getAlertInMillisFromDB);

        int intHour = getHour();
        int intMin = getMin();
        int intDay = getDay();
        int intMonth = getMonth();
        int intYear = getYear();
        String alertStringInMills = getStringAlertInMillis();

        System.out.println("SERVICE --- resetAlarm");
        System.out.println("SERVICE --- year "+intYear);
        System.out.println("SERVICE --- month "+intMonth);
        System.out.println("SERVICE --- day "+intDay);
        System.out.println("SERVICE --- hour "+intHour);
        System.out.println("SERVICE --- min "+intMin);


        updateAlert(id, eventName, getAlertInMinutesFromDB,
                getAlertInMillisFromDB, intYear, intMonth, intDay, intHour,
                intMin);


    }


    public void updateAlert(int id, String name,
             final String minutes,
            final String alertTime, int intYear, int intMonth, int intDay,
            int intHour, int intMin) {

          Intent osa = new Intent(AlarmsService.this.getApplicationContext(), OneShotAlarm.class);
          String idStringFormat=""+id+"";
          String warning="In "+ minutes +" Minutes";
          osa.putExtra("name", name);
          osa.putExtra("text", warning);
          osa.putExtra("id", idStringFormat);                 
          sender = PendingIntent.getBroadcast(AlarmsService.this.getApplicationContext(), id, osa, 0);
          am = (AlarmManager) getSystemService(ALARM_SERVICE);



        Calendar calendar = Calendar.getInstance();

        calendar.setTimeInMillis(System.currentTimeMillis());
        System.out.println( "SERVICE --- current time in millis" +calendar.getTimeInMillis());
        calendar.clear();
        //
        TimeZone timeZone = calendar.getTimeZone();
        calendar.setTimeZone(timeZone);

        calendar.set(intYear, intMonth, intDay, intHour, intMin, 0);

        System.out.println( "SERVICE --- Alert time in millis" +calendar.getTimeInMillis());

        am.cancel(sender);
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

    }}

Broadcast Receiver:

package com.google.android.gcm.demo.app.Alerts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class AlarmsBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "BootReceiver";



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


        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) 
        {
//      if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {

        Intent  startServiceIntent = new Intent(context, AlarmsService.class);
              context.startService(startServiceIntent);
                Log.d("TAG", "TestBroadcastReceiver");


               System.out.println( "test broadcast reciver...");   



        }



    }

}

Logcat:

09-16 14:29:10.270: D/Exchange(263): BootReceiver onReceive
09-16 14:29:10.280: D/EAS SyncManager(263): !!! EAS SyncManager, onCreate
09-16 14:29:10.381: D/EAS SyncManager(263): !!! EAS SyncManager, onStartCommand
09-16 14:29:10.410: D/EAS SyncManager(263): !!! EAS SyncManager, stopping self
09-16 14:29:10.510: D/dalvikvm(203): GC_FOR_MALLOC freed 4559 objects / 383904 bytes in 66ms
09-16 14:29:10.551: I/CheckinService(203): Preparing to send checkin request
09-16 14:29:10.574: D/Eas Debug(263): Logging: 
09-16 14:29:10.580: D/EAS SyncManager(263): !!! EAS SyncManager, onDestroy
09-16 14:29:10.641: I/EventLogService(203): Accumulating logs since 1347819701556
09-16 14:29:11.040: D/dalvikvm(116): GC_EXTERNAL_ALLOC freed 3626 objects / 202712 bytes in 83ms
09-16 14:29:11.350: I/ActivityManager(58): Start proc com.android.alarmclock for broadcast com.android.alarmclock/.AlarmInitReceiver: pid=277 uid=10035 gids={}
09-16 14:29:11.390: D/MediaScannerService(224): start scanning volume internal
09-16 14:29:11.760: I/ActivityThread(277): Publishing provider com.android.alarmclock: com.android.alarmclock.AlarmProvider
09-16 14:29:11.900: I/ActivityManager(58): Start proc com.google.android.gcm.demo.app for broadcast com.google.android.gcm.demo.app/.Alerts.AlarmsBroadcastReceiver: pid=285 uid=10040 gids={3003, 1015}
09-16 14:29:12.200: D/TAG(285): TestBroadcastReceiver
09-16 14:29:12.200: I/System.out(285): test broadcast reciver...
09-16 14:29:12.280: I/alerttService(285): Service created...
09-16 14:29:12.280: D/TAG(285): started onstart command Created from Alerts service .
09-16 14:29:12.300: I/alerttService(285): Service started...
09-16 14:29:12.330: I/System.out(285): SERVICE -----start thread
09-16 14:29:12.480: I/System.out(285): database opened android.database.sqlite.SQLiteDatabase@44f27188
09-16 14:29:12.510: I/System.out(285): database closed 
09-16 14:29:12.510: I/System.out(285): SERVICE ----eventName from service Super GALS 1-4
09-16 14:29:12.510: I/System.out(285): SERVICE ----id from service 1
09-16 14:29:12.510: I/System.out(285): SERVICE ----alertDuration from service 30
09-16 14:29:12.510: I/System.out(285): SERVICE ----alert UTC Time from alertInMills 2012-09-16T08:30:00.000-04:00
09-16 14:29:12.510: I/System.out(285): SERVICE ---- eventState from service 0
09-16 14:29:12.510: I/System.out(285): SERVICE --- resetAlarm
09-16 14:29:12.510: I/System.out(285): SERVICE --- year 2012
09-16 14:29:12.510: I/System.out(285): SERVICE --- month 9
09-16 14:29:12.510: I/System.out(285): SERVICE --- day 16
09-16 14:29:12.510: I/System.out(285): SERVICE --- hour 8
09-16 14:29:12.510: I/System.out(285): SERVICE --- min 30
09-16 14:29:12.560: I/System.out(285): SERVICE --- current time in millis1347820152568
09-16 14:29:12.630: I/System.out(285): SERVICE --- Alert time in millis1350390600000
09-16 14:29:12.630: I/System.out(285): SERVICE ----eventName from service Super GALS 1-4
09-16 14:29:12.640: I/System.out(285): SERVICE ----id from service 2
09-16 14:29:12.640: I/System.out(285): SERVICE ----alertDuration from service 20
09-16 14:29:12.640: I/System.out(285): SERVICE ----alert UTC Time from alertInMills 2012-09-16T08:40:00.000-04:00
09-16 14:29:12.640: I/System.out(285): SERVICE ---- eventState from service 0
09-16 14:29:12.640: I/System.out(285): SERVICE --- resetAlarm
09-16 14:29:12.640: I/System.out(285): SERVICE --- year 2012
09-16 14:29:12.640: I/System.out(285): SERVICE --- month 9
09-16 14:29:12.640: I/System.out(285): SERVICE --- day 16
09-16 14:29:12.640: I/System.out(285): SERVICE --- hour 8
09-16 14:29:12.640: I/System.out(285): SERVICE --- min 40
09-16 14:29:12.640: I/System.out(285): SERVICE --- current time in millis1347820152650
09-16 14:29:12.650: I/System.out(285): SERVICE --- Alert time in millis1350391200000
09-16 14:29:12.650: I/System.out(285): SERVICE ----eventName from service Teeny Witches
09-16 14:29:12.650: I/System.out(285): SERVICE ----id from service 3
09-16 14:29:12.650: I/System.out(285): SERVICE ----alertDuration from service 30
09-16 14:29:12.650: I/System.out(285): SERVICE ----alert UTC Time from alertInMills 2012-09-16T02:36:00.000-04:00
09-16 14:29:12.650: I/System.out(285): SERVICE ---- eventState from service 0
09-16 14:29:12.650: I/System.out(285): SERVICE --- resetAlarm
09-16 14:29:12.650: I/System.out(285): SERVICE --- year 2012
09-16 14:29:12.650: I/System.out(285): SERVICE --- month 9
09-16 14:29:12.650: I/System.out(285): SERVICE --- day 16
09-16 14:29:12.650: I/System.out(285): SERVICE --- hour 2
09-16 14:29:12.650: I/System.out(285): SERVICE --- min 36
09-16 14:29:12.661: I/System.out(285): SERVICE --- current time in millis1347820152662
09-16 14:29:12.661: I/System.out(285): SERVICE --- Alert time in millis1350369360000
09-16 14:29:12.661: I/System.out(285): SERVICE ----eventName from service Parents and Anime
09-16 14:29:12.661: I/System.out(285): SERVICE ----id from service 4
09-16 14:29:12.661: I/System.out(285): SERVICE ----alertDuration from service 10
09-16 14:29:12.661: I/System.out(285): SERVICE ----alert UTC Time from alertInMills 2012-09-16T01:50:00.000-04:00
09-16 14:29:12.661: I/System.out(285): SERVICE ---- eventState from service 0
09-16 14:29:12.661: I/System.out(285): SERVICE --- resetAlarm
09-16 14:29:12.661: I/System.out(285): SERVICE --- year 2012
09-16 14:29:12.661: I/System.out(285): SERVICE --- month 9
09-16 14:29:12.661: I/System.out(285): SERVICE --- day 16
09-16 14:29:12.661: I/System.out(285): SERVICE --- hour 1
09-16 14:29:12.661: I/System.out(285): SERVICE --- min 50
09-16 14:29:12.670: I/System.out(285): SERVICE --- current time in millis1347820152673
09-16 14:29:12.670: I/System.out(285): SERVICE --- Alert time in millis1350366600000
09-16 14:29:12.670: I/System.out(285): SERVICE ----eventName from service Mobile Suit Gundam Movie 1
09-16 14:29:12.670: I/System.out(285): SERVICE ----id from service 5
09-16 14:29:12.670: I/System.out(285): SERVICE ----alertDuration from service 50
09-16 14:29:12.670: I/System.out(285): SERVICE ----alert UTC Time from alertInMills 2012-09-16T14:10:00.000-04:00
09-16 14:29:12.670: I/System.out(285): SERVICE ---- eventState from service 0
09-16 14:29:12.696: I/System.out(285): SERVICE --- resetAlarm
09-16 14:29:12.696: I/System.out(285): SERVICE --- year 2012
09-16 14:29:12.696: I/System.out(285): SERVICE --- month 9
09-16 14:29:12.696: I/System.out(285): SERVICE --- day 16
09-16 14:29:12.696: I/System.out(285): SERVICE --- hour 14
09-16 14:29:12.696: I/System.out(285): SERVICE --- min 10
09-16 14:29:12.700: I/System.out(285): SERVICE --- current time in millis1347820152704
09-16 14:29:12.700: I/System.out(285): SERVICE --- Alert time in millis1350411000000
09-16 14:29:12.700: I/System.out(285): SERVICE ----eventName from service To Love Ru 1-4
09-16 14:29:12.700: I/System.out(285): SERVICE ----id from service 6
09-16 14:29:12.700: I/System.out(285): SERVICE ----alertDuration from service 10
09-16 14:29:12.700: I/System.out(285): SERVICE ----alert UTC Time from alertInMills 2012-09-16T14:50:00.000-04:00
09-16 14:29:12.700: I/System.out(285): SERVICE ---- eventState from service 0
09-16 14:29:12.700: I/System.out(285): SERVICE --- resetAlarm
09-16 14:29:12.700: I/System.out(285): SERVICE --- year 2012
09-16 14:29:12.710: I/System.out(285): SERVICE --- month 9
09-16 14:29:12.710: I/System.out(285): SERVICE --- day 16
09-16 14:29:12.710: I/System.out(285): SERVICE --- hour 14
09-16 14:29:12.710: I/System.out(285): SERVICE --- min 50
09-16 14:29:12.710: I/System.out(285): SERVICE --- current time in millis1347820152717
09-16 14:29:12.710: I/System.out(285): SERVICE --- Alert time in millis1350413400000

Solution

  • Maybe it is because you are getting a Broadcast Pending intent instead of Service Pending intent

    Instead of

    PendingIntent.getBroadcast
    

    use

    PendingIntent.getService 
    

    Also difference between your current time and set time is somewhere nearer to 29 days. Are you sure it is correct.

    In calendar , when you set month, month starts from 0 and not from 1. September is 8 and not 9, which looks to be the value you are setting.