Notification with alarm manager

0

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

The goal is to show a notification after 10 seconds but I'm not receiving any kind of 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 through 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>
    
asked by anonymous 16.06.2016 / 16:28

1 answer

0

You are creating PendingIntent in the wrong way.
PendingIntent is a mechanism which Android uses to allow an external application (NotificationManager, AlarmManager, and others) to use the permissions of your application to execute a predefined code.

It provides several static methods to use according to the type of code to execute.

In this case, how you want to run a BradcastReceiver, you should use the PendingIntent.getBroadcast () and not PendingIntent.getActivity () that should be used when launching an Activity.

Replace the line

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

by

alarmIntent = PendingIntent.Broadcast(context, 0, intent, 0);
    
16.06.2016 / 18:12