How to make it work in the background?

1

I have an App that shows Toast indefinitely, how can I do it in the background even without using it?

    
asked by Rf Mvs 02.10.2016 в 17:03
source

2 answers

1

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.

example: how to create a notification:

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());

    
answered by 02.10.2016 в 18:53
-1

You could use a thread, check this maybe it can help you! AsyncTask: Asynchronous Tasks on Android

    
answered by 02.10.2016 в 17:35