0

I am trying to create a task to send a notification everyday at 1:00 am. the task should run even if the application is off.

I have used Service and AlarmManager to do the job. But the problem is that the task is executed once and whenever the application gets on. I guess that the service is killed for resources allocation.

my question is how to implement the schedule task to keep working and activate itself even if it is killed, and how to get the task schedule at the time of app installation. currently, I put the initiation at main activity.

Here a snippets from the code: I appreciate any help regarding this:

public class MyAlarmService extends Service{

     private NotificationManager mManager;

     @Override
     public IBinder onBind(Intent arg0){
       // TODO Auto-generated method stub
        return null;
     }

    @Override
    public void onCreate(){
       // TODO Auto-generated method stub  
       super.onCreate();
    }


    @Override
    public int onStartCommand(final Intent intent, final int flags,
            final int startId) {


       mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
       Intent intent1 = new Intent(this.getApplicationContext(),TabsFragmentActivity.class);
       intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

       PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,
                                                                PendingIntent.FLAG_UPDATE_CURRENT );
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = " Here is the share content body";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);

       PendingIntent pendingIntent =PendingIntent.getActivity(this, 0,Intent.createChooser(sharingIntent, getResources().getString(R.string.choose_share_action)), 
                                                                PendingIntent.FLAG_UPDATE_CURRENT);


       String msgText = "Notification long text example!! "
                + "where you will see three different kind of notification. "
                + "you can even put the very long string here.";


       int icon = R.drawable.ic_launcher;

          Builder builder = new Notification.Builder(this);
          builder.setContentTitle(getResources().getString(R.string.noticifcation_content_title))
            .setContentText("This is the compact version")
            .setContentIntent(pendingNotificationIntent)
            .setTicker(getResources().getString(R.string.noticifcation_ticker))
            .setSmallIcon(icon)
            .setAutoCancel(false)
            .setPriority(Notification.PRIORITY_DEFAULT)
            .addAction(R.drawable.ic_action_share, 
                    getResources().getString(R.string.share),pendingIntent);
          Notification notification = new Notification.BigTextStyle(builder)
            .bigText(msgText).build();

          mManager.notify(0, notification);

    }

Receiver:

public class MyReceiver extends BroadcastReceiver{

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

       Intent service = new Intent(context, MyAlarmService.class);
       context.startService(service);

     }
}

private void createNotification() {
        Calendar calendar = Calendar.getInstance();   

        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM,Calendar.AM);

        Intent myIntent = new Intent(TabsFragmentActivity.this, MyReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(TabsFragmentActivity.this, 0, myIntent,0);

        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES , pendingIntent); 
    }
Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177
  • Have you got the answer ? I too have same kind of problem:https://stackoverflow.com/questions/45007981/alarmmanager-is-not-executing-the-class-in-time/45008468?noredirect=1#comment76993769_45008468 – Sidhartha Jul 10 '17 at 12:42

3 Answers3

0

all you need to do in order to start a service when the app comes to life is to extend the Application class and in the onCreate start your service.

class MyApplication extends Application {

  @Override
  public void onCreate() {
    Intent service = new Intent(MyApplication.this, MyAlarmService.class);
    startService(service);
  }
}
thepoosh
  • 12,497
  • 15
  • 73
  • 132
  • this will allow my service to start once I install the app, but what about the scheduling to run everyday, it is still in main activity, do I have to alter it to? how? – user3004702 Jan 02 '14 at 08:25
  • int the service you can always register to the `AlarmManager` – thepoosh Jan 02 '14 at 08:32
0

You have have detemined the amount of time (interval) to execute a snippet of code, its better to use AlarmManager because its more energy effient. If your app needs to listen to some sort of a event , then Service is what you need. this code is running a background task every 15 minutes, even when application is not runninng

public static void registerAlarm(Context context) {
     Intent i = new Intent(context, YOURBROADCASTRECIEVER.class);

     PendingIntent sender = PendingIntent.getBroadcast(context,REQUEST_CODE, i, 0);

     // We want the alarm to go off 3 seconds from now.
     long firstTime = SystemClock.elapsedRealtime();
     firstTime += 3 * 1000;//start 3 seconds after first register.

     // Schedule the alarm!
     AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
     am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
                     600000, sender);//10min interval

}

Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • where do you add this method... currently I have one in main activity, which I believe it is not the best solution. I think I need to combine your solution with "thepoosh"'s solution... I will try it . – user3004702 Jan 02 '14 at 08:26
  • http://karanbalkar.com/2013/07/tutorial-41-using-alarmmanager-and-broadcastreceiver-in-android/ – Yanshof Jan 02 '14 at 08:29
0

you have to implement BOOT_COMPLATE Receiver.

as well when your app start first time start service if service is already running then do nothing.

you can also use other Actions to check service is running or not like media scanner

Community
  • 1
  • 1
Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177