W
W
wolfak2016-04-03 20:27:40
Android
wolfak, 2016-04-03 20:27:40

How to create notification in android service?

Good evening. I need to create a service that would check every 1-3 minutes for new private messages. (site client application) I can write the check for new messages without problems, but I don’t understand how to make such a service and implement the creation of notifications in it.
I tried a lot of ways, but all cause an error, most often associated with PendingIntent, because when you click on a notification, you need to make a transition to a new activity.
I call like this, in mainActivity:

private void restartNotify() {
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, TimeNotification.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT );
        am.cancel(pendingIntent);
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pendingIntent);
    }

The class code itself:
public class TimeNotification extends BroadcastReceiver {

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

            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, mainfeed.class), 0);
            Resources res = context.getResources();
            Notification.Builder builder = new Notification.Builder(context)
                    .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.mediumico))
                    .setContentTitle("My App")
                    .setContentText("TextAllers")
                    .setContentIntent(contentIntent)
                    .setSmallIcon(R.drawable.mediumico)
                    .setAutoCancel(true);
            NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = builder.getNotification();
            notificationManager.notify(333, notification);

            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                    intent, PendingIntent.FLAG_CANCEL_CURRENT);
            am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 180000, pendingIntent);

}

I hope for your help, I need a simple example of creating notifications from a service and automatically starting the service every 1-3 minutes. I spent a lot of time searching, but to no avail. Many thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2016-04-04
@wolfak

To restart, you need to use the AlarmManager and BroadcastReceiver.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question