Search code examples
androidnotificationsbroadcastreceiveralarmmanager

How should I run a service daily and 12pm using alarmmanager


I am trying to open a new service daily at 7 pm that would notify me on startup but i cant resolve this problem and cant understand why. can anyone help me out thankx Here is the code


Here is the code i wrote in the DaysCounterActivity class

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 19);
    calendar.set(Calendar.MINUTE, 05);
    calendar.set(Calendar.SECOND, 00);


    Intent intent = new Intent(this, MyReciever.class);
    PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);


    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pintent);

and here is MyReviever class onRevcieve method

    public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    Intent serviceIntent = new Intent();
    serviceIntent.setAction("com.saaram.MyService");
    context.startService(serviceIntent);
}

Solution

  • Your problem is that pintent is trying to run a Service, but MyReceiver is a Broadcast Receiver. It would work if you changed MyReceiver to a Service.

    public class MyReceiver extends Service {
    
    
        public int onStartCommand(Intent intent, int flags, int startId) {
            //Anything you put here is run at the time you set the alarm to
            }
    
        @Override
        public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
            return null;
            }
    
        }
    

    In your manifest you would just declare it like so:

    <service android:name=".MyReceiver"></service>