Pritesh Pritesh - 1 year ago 237
Android Question

AlarmManager getting killed with the app

I created an app to send message using alarm manager but if i put an alarm for a long duration the app is killed by android automatically, so i need to prevent the app from getting killed.Please tell me how can I do it.

Calendar cal = Calendar.getInstance();
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
if (currentApiVersion > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
cal.set(Calendar.MINUTE, time_picker.getMinute());
cal.set(Calendar.HOUR_OF_DAY, time_picker.getHour());
} else {
//Setting the date and time from the time picker
cal.set(Calendar.MINUTE, time_picker.getCurrentMinute());
cal.set(Calendar.HOUR_OF_DAY, time_picker.getCurrentHour());
//System clock time
Calendar c = Calendar.getInstance();
Long a ;//=(long) (Calendar.getInstance().get(Calendar.SECOND) * 1000);
if(cal.get(Calendar.HOUR_OF_DAY) < c.get(Calendar.HOUR_OF_DAY))
h = (cal.get(Calendar.HOUR_OF_DAY) + 24 - c.get(Calendar.HOUR_OF_DAY)) * 60;
h = (cal.get(Calendar.HOUR_OF_DAY) - c.get(Calendar.HOUR_OF_DAY * 60;
m = (cal.get(Calendar.MINUTE) - c.get(Calendar.MINUTE));
a = (m + h) * 60;
myIntent = new Intent(this, MyReceiver.class);

//Pending Intent for sending the intent afterwards
pendingIntent[] = PendingIntent.getBroadcast(this.getApplicationContext(),, myIntent, 0);
alarmManager[] = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
alarmManager[].set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + a * 1000, pendingIntent[]);

sms_list.Phone[] = Phone;
Intent back = new Intent(this, sms_list.class);
back.putExtra("PHONE", Phone);
back.putExtra("MSG", Message);
back.putExtra("HOUR", (int) cal.get(Calendar.HOUR_OF_DAY));
back.putExtra("MIN", (int) cal.get(Calendar.MINUTE));

If the answer is wake lock can you please tell me where to use it.

Answer Source

An alarm should be triggered in a Broadcast Receiver.

If it performs long-lived operations, you should then use threads or Services. Both of them can be launched from a receiver.


As a short example, I use this method in a button's onClickListener in the activity :


Method :

public void scheduleAlarm(String client)
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String delay = sharedPref.getString(SettingsActivity.PREF_DELIVERY_DELAY, "48");

// time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
// we fetch  the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000   milliseconds in a day
Long time = new GregorianCalendar().getTimeInMillis()+ Integer.parseInt(delay) * 1000; //todo change seconds to hours

// create an Intent and set the class which will execute when Alarm triggers, here we have
// given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers and
//we will write the code to send SMS inside onRecieve() method pf Alarmreciever class
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
intentAlarm.putExtra("CLIENT", client);

// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

//set the alarm for particular time
//todo string res
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled in " + delay + " hours", Toast.LENGTH_LONG).show();


And finally, the

package com.patrickmiller.test2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent)
        Toast.makeText(context, "Alarm received", Toast.LENGTH_SHORT).show();

        String client = intent.getStringExtra("CLIENT");

        Notify(context, client);

    public void Notify(Context context, String client) {

        //todo expanded layout with options Fiche de contact | Rapport and cover image
        //todo send name, address, phone, email and id through Intent to ContactClientActivity
        //todo delete notification when generated

        try {
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(context)
                            //todo set notification icon, content title and content text as string resources
                            .setContentText("N'oubliez pas de générer le rapport du client");

            Intent resultIntent = new Intent(context, ContactClientActivity.class);

            //todo may need to expend instead of calling activity. Buttons will do.
            // Because clicking the notification opens a new ("special") activity, there's
            // no need to create an artificial back stack.
            PendingIntent resultPendingIntent =


            // Sets an ID for the notification
            int mNotificationId = 001;

            // Gets an instance of the NotificationManager service
            NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

            // Builds the notification and issues it.


        catch(Exception e) {
            Toast.makeText(context, String.valueOf(e), Toast.LENGTH_LONG).show();



You don't have to care about the client's thing. Just the way I scheduled the alarm..

My operation is a short-lived one, which is sending a notification. If you plan a long-lived operation, you should start a service or a thread from the receiver (onReceive callback method).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download