I have an App that shows Toast indefinitely, how can I do it in the background even without using it?
I have an App that shows Toast indefinitely, how can I do it in the background even without using it?
A toast can not be created when it is in the background since it needs the context of the application or activity to be created.
One option would be to create a notification generated by a service in which the context is the same service as the class Service extends from Context.
public static void creaNotificacion(long when, String notificationTitle,
String notificationContent, String notificationUrl, Context ctx) {
try {
Intent notificationIntent;
Bitmap largeIcon = BitmapFactory.decodeResource(ctx.getResources(),
R.drawable.ic_launcher);
int smalIcon = R.drawable.ic_launcher;
/* Valida la url y crea un Intent */
if (!"".equals(notificationUrl)) {
notificationIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(notificationUrl));
} else {
notificationIntent = new Intent();
}
/* Crea PendingIntent */
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);
/* Construye la notificacion */
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
ctx).setWhen(when).setContentText(notificationContent)
.setContentTitle(notificationTitle).setSmallIcon(smalIcon)
.setAutoCancel(true).setTicker(notificationTitle)
.setLargeIcon(largeIcon)
.setContentIntent(pendingIntent);
notificationManager.notify((int) when, notificationBuilder.build());
} catch (Exception e) {
Log.e("Notificacion", "createNotification::" + e.getMessage());
}
}
and this is an example of how to call the method to create the notification, it would be the way to do it when a user has selected a certain command, the notification will appear:
creaNotificacion(0,"Notificación Android!","Como llamar a una alerta o notificación para el usuario en la aplicación de Android?", "http://es.stackoverflow.com", getApplicationContext());
You could use a thread, check this maybe it can help you! AsyncTask: Asynchronous Tasks on Android