Broadcast notification when Android device is asleep

Asked

Viewed 1,503 times

1

I have a Activity calling a function of a class (service) that creates a intent = NEW INTENT("MEU_BROADCAST") and also a Alarmmanager. Within the class Broadcast I call a Activity creating a notification.

Everything working perfectly, my problem is that I want it to wake up even when the user clicks the button power (Sleep), because it does not wake up if it is asleep, only when the user clicks on the power to turn on the screen. I tried to use the Powermanager It’s just not working! Can someone help me?

This function is of my class that does not extend anything! is just a function I call via an OBJECT

public void gravarAlertaDeEvento(Context ctx, int alarmId, int mHour, int mMinute, boolean repeat, Calendar calendar, String titulo, String evento, boolean som)
{
    //Intent intentAlarme = new Intent(ctx, Alarme.class);
    Intent intentAlarme = new Intent("EXECUTAR_ALARME");
    //intentAlarme.setAction("Start");
    intentAlarme.putExtra("id_evento", ""+alarmId);
    intentAlarme.putExtra("musica", som);
    intentAlarme.putExtra("titulo_evento", titulo); //Insere titulo do evento salvo
    intentAlarme.putExtra("evento", evento);    //insere info do evento salvo
    //PendingIntent enviarAlarme = PendingIntent.getActivity(ctx, alarmId, intentAlarme, 0);
    PendingIntent enviarAlarme = PendingIntent.getBroadcast(ctx, alarmId, intentAlarme, 0);

    AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    if(repeat)
    {
        am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), calendar.getTimeInMillis(), enviarAlarme);
    }else
    {
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), enviarAlarme); 
    }   
}   

My Service class:

public class GerandoNotificacao extends Service{

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

@SuppressWarnings("deprecation")
public void onStart(Intent intent, int startId){
    super.onStart(intent, startId);

    try {

        String titulo = intent.getStringExtra("titulo_evento");
        String assunto = intent .getStringExtra("evento");

        NotificationManager notManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notific = new Notification(R.drawable.calendar2, "Evento", System.currentTimeMillis());

        if (intent.getBooleanExtra("musica", false))
        {
            notific.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/"+ R.raw.alarme);
        }           

        notific.defaults = Notification.DEFAULT_LIGHTS;
        notific.flags |= Notification.FLAG_INSISTENT;
        notific.flags |= Notification.FLAG_AUTO_CANCEL;

        notific.ledARGB = R.color.seaGreen;

        notific.vibrate = new long[]{ 100, 250, 100, 250, 100, 250, 100, 250, 500 };

        int idEvento = Integer.parseInt(intent.getStringExtra("id_evento")); //pegando id da notificação

        Intent activityAbrir = new Intent(this, EditarEvento.class);
        activityAbrir.putExtra("tela", "eventos");
        activityAbrir.putExtra("p_c", ""+idEvento);
        activityAbrir.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);   

        //PendingIntent para executar a Activity se o usuário selecionar a notificação
        PendingIntent pendInt = PendingIntent.getActivity(this, idEvento, activityAbrir, 0);

        notific.setLatestEventInfo(getApplicationContext(), titulo, assunto, pendInt);
        notManager.notify(idEvento, notific);       

        WakefulBroadcastReceiver.completeWakefulIntent(intent);

    } catch (Exception e) {
        //Toast.makeText(getApplicationContext(), "Alert: "+e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

}

My class Wakeupfullbroadcastreceved

@Override
public void onReceive(Context c, Intent i) {

    Intent intet = new Intent(c, GerandoNotificacao.class); //Chamando a classe notificação
    intet.putExtra("id_evento", i.getStringExtra("id_evento"));      //insere id do evento (banco de dados)
    intet.putExtra("musica", i.getBooleanExtra("musica", false));
    intet.putExtra("titulo_evento", i.getStringExtra("titulo_evento")); //Insere titulo do evento salvo
    intet.putExtra("evento", i.getStringExtra("evento"));   //insere info do evento salvo

    /*try {
        this.finalize();
    } catch (Throwable e) { Log.i("Erro borad: ", e.getMessage());  }*/
    startWakefulService(c, intet);        
}

My Manifest

<receiver android:name="br.com.AlarmeEvento.Alarme" >
        <intent-filter>
            <action android:name="EXECUTAR_ALARME" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

1 answer

0


Who has to have a Wake Lock to keep the CPU awake is the broadcast receiver and not the code that schedules the alarm next to Alarmmanager. I suggest your broadcast receiver be a subclass of Wakefulbroadcastreceiver. If the alarm trigger (sound to be played, etc.) is performed within a separate service and not directly on onReceive(), the service before finalizing should call WakefulBroadcastReceiver.completeWakefulIntent(intent) so that Wake Lock can be released.

  • Two problems: the line intet.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); must be removed and the call am.setRepeating() uses the parameter calendar.getTimeInMillis() twice (should not be used the second time, but a value in milliseconds for the repeat interval: if daily, this value should be for example 24 * 60 * 60 * 1000 which is the amount of milliseconds in a day). Something tells me your class GerandoNotificacao is a Activity and not a Service, she should be a Service. Post her code also in the question. Include a line Log.i() in it and see if it is executed.

  • This Calendar.getTimeInMillis() is from the calendar I passed via parameter, so I think it is not a problem! It has these two because maybe the user wanted it to repeat the alarm so I have a setRepeat() and a normal set() ! @Piovezan

  • Have you stopped to understand what these two parameters are for? The first is the time the alarm must go off and the second is the REPEAT INTERVAL. It’s an interval Alarmmanager will wait for before firing again, not a date. If and your intention is for the alarm to repeat every day at the same time, use the amount I mentioned.

  • In your service instead of the method onStart() which is obsolete and is no longer called by the system, use onStartCommand(). Thus: @Override public int onStartCommand (Intent intent, int flags, int startId) { super.onStartcommand(intent, flags, startId); and make it return anything, for example return START_NOT_STICKY;.

  • And by all means, if this works, accept my reply by clicking on the accept icon as in this example: http://i.stack.Imgur.com/uqJeW.png

  • @Piovezan worked perfectly on cell phone only my brother! Only on mine that does not! I think Sony is blocking kkkkkk! But I’ll do other tests with other phones! Now my problem is: if the user deletes the event before it happens I need to cancel this alarm! As I should proceed, you know?

  • 1

    If the problem is another, open another question. The site works like this: a question by problem. :)

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.