Los que llevamos un tiempo con Linux en general conocemos el termino de Daemon o demonio y la gente de Windows los conoce como servicios. Son programas que están en segundo plano ejecutándose, esperando algún tipo de llamada o evento para ser lanzados.
public class ExampleService extends Service {
private Timer mTimer = null;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate(){
super.onCreate();
this.mTimer = new Timer();
this.mTimer.scheduleAtFixedRate(
new TimerTask(){
@Override
public void run() {
ejecutarTarea();
}
}
, 0, 1000 * 60);
}
private void ejecutarTarea(){
Thread t = new Thread(new Runnable() {
public void run() {
NotifyManager notify = new NotifyManager();
notify.playNotification(getApplicationContext(),
HolaMundoActivity.class, "Tienes una notificación"
, "Notificación", R.drawable.img_notify);
}
});
t.start();
}
}
public class NotifyManager {
public void playNotification(Context context, Class<?> cls, String textNotification, String titleNotification, int drawable){
/*NOTIFICATION VARS*/
NotificationManager mNotificationManager;
int SIMPLE_NOTIFICATION_ID = 1;
Notification notifyDetails;
/*NOTIFICATION INICIO*/
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifyDetails = new Notification(drawable,titleNotification,System.currentTimeMillis());
long[] vibrate = {100,100,200,300};
notifyDetails.vibrate = vibrate;
notifyDetails.defaults = Notification.DEFAULT_ALL;
notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
/*NOTIFICATION FIN*/
CharSequence contentTitle = titleNotification;
CharSequence contentText = textNotification;
Intent notifyIntent = new Intent(context, cls );
notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(context, 0, notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.tickerText = textNotification;
notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
try{
mNotificationManager.notify(SIMPLE_NOTIFICATION_ID, notifyDetails);
} catch(Exception e){
}
}
}
<service android:name=".ExampleService" />
Por último tenemos que lanzar nuestro servicio, para ello en la primera Activity que ejecute nuestra aplicación en el onCreate ejecutamos lo siguiente.
Intent service = new Intent(this, ExampleService.class);
startService(service);