Search code examples
androidservicenotificationsalarmmanageralarm

my alarm service run several times and not in actual time


i have an alarm service that works with alarm manager. it's works correctly when you set alarm for later. but when you set it for past ( you want to alert you tomorrow) it gone crazy and alert several times instead of once and finally wont work tomorrow. some one plz help me on this.

i do like this: I have a alarm class. when i create it, so it make an pending intent that run a service with alarm manger. and the service will open my activity.

is it the wrong way?

here is my alarm class:

public class MyAlarm  {

    private Context myContext;
    private NotificationManager mNM;
    private int NOTIFICATION = 10002; //Any unique number for this notification

    MyAlarm(Context myAct){



        myContext = myAct;
        showNotification();





    }
     // this constractor is for cancelling alarm

    MyAlarm(Context myAct, String str) {
        myContext = myAct;
        cancelPendigIntent();
    }

    private void cancelPendigIntent() {


        //Intent myIntent = new Intent(myContext, MyAlarmService.class);
        //G.pendingIntent = PendingIntent.getService(myContext, 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        //G.pendingIntent.cancel();
        //G.alarmManager.cancel(G.pendingIntent);

    }

    private void showNotification() {



         Intent myIntent = new Intent(myContext, MyAlarmService.class);
         G.pendingIntent = PendingIntent.getService(myContext, 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
         G.alarmManager = (AlarmManager)myContext.getSystemService(Context.ALARM_SERVICE);
         G.calendar = Calendar.getInstance();

         int to_day= G.calendar.get(Calendar.DATE);
         int to_mounth= G.calendar.get(Calendar.MONTH);
         int to_year= G.calendar.get(Calendar.YEAR);
         G.calendar.set(to_year, to_mounth, to_day, Integer.parseInt(G.myPref.loadString("alert_time_houre")), Integer.parseInt(G.myPref.loadString("alert_time_mins")), 0);
         Log.i("LOG", "alert_time_houre="+G.myPref.loadString("alert_time_houre")+"  alert_time_mins="+G.myPref.loadString("alert_time_mins"));
         G.alarmManager.setRepeating(AlarmManager.RTC, G.calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, G.pendingIntent);




    }

Solution

  • i finally find the answer.

    my problem is not about alarm manager. i set the pendig intent to a service that opens a activity. the problem was while the service is run in background it opened my activity again and again and my app go crazy. maybe i should destroy the service after her job done once.

    i change it from service to broadcastreceiver and it's works correctly.

    thanks for guides :)