Answer the question
In order to leave comments, you need to log in
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);
}
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);
}
Answer the question
In order to leave comments, you need to log in
To restart, you need to use the AlarmManager and BroadcastReceiver.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question