Example of a service that send a notification
package com.xanderco.serviceapp;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
public class MyService extends IntentService {
public static final String MESSAGE = "message";
public static final int NOTIFICATION_ID = 1325;
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
//Syncronized es usado para que java ejecute este codigo obligatoriamente y no ejecute el otro codigo en diferenntes Threads
synchronized (this) {
try {
wait(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String text = intent.getStringExtra(MESSAGE);
showText(text);
}
}
// Este es un metodo creado para recibir una mensaje y enviar la notificacion
private void showText(final String text) {
Intent intent = new Intent(this, MainActivity.class);
TaskStackBuilder stackbuilder = TaskStackBuilder.create(this);
stackbuilder.addParentStack(MainActivity.class);
stackbuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackbuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Hello")
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setDefaults(Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent)
.setContentText(text)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID,notification);
}
}