Notification with Alarm manager

Asked

Viewed 679 times

0

One of the ultimate goals of my application is to send notifications to the user at a certain time. My Alarm manager is working correctly now my problem is notifications that are not shown.

The aim is to show a notification after 10 seconds but I am not receiving any notification.

My code to send notifications:

public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager mNM;
    mNM = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = new Notification(R.drawable.ic_launcher, "Teste",
            System.currentTimeMillis());

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);

    notification.setLatestEventInfo(context, "TESTE" , "Teste", contentIntent);

    mNM.notify(0, notification);
}

}

I call the receiver by my Alarm manager :

 PendingIntent alarmIntent;


            Intent intent = new Intent(context, AlarmReceiver.class);
            alarmIntent = PendingIntent.getActivity(context, 0, intent, 0);

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.SECOND, 10);
            long firstTime = calendar.getTimeInMillis();


            AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, firstTime, alarmIntent);

I added it to my Androidmanifest.xml :

<receiver android:process=":remote" android:name="AlarmReceiver"></receiver>
  • You left } out of Tiago formatting.

1 answer

0


You are creating Pendingintent wrong.
Pendingintent is a mechanism that Android uses to allow an external application(Notificationmanager, Alarmmanager and others) use the permissions of your application to run a predefined code.

It provides several static methods to be used according to the type of code to be executed.

In this case, as you want to execute a Bradcastreceiver, you must use the method Pendingintent.getBroadcast() and not Pendingintent.getActivity() to be used when launching an Activity.

Replace the line

alarmIntent = PendingIntent.getActivity(context, 0, intent, 0);

for

alarmIntent = PendingIntent.Broadcast(context, 0, intent, 0);

Browser other questions tagged

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