How to send notification without opening the application

Asked

Viewed 2,823 times

2

I need to send a notification every time someone requests friendship. How to create this notification I already know but I made a test app that sends through the action of a button. In this case the user who will receive may not have the app open. How do I send this notification? I make a thread that runs at every given time?

  • What kind of notification are you referring to? These are the ones that appear on notification Drawer, at the top of the screen?

  • Explain how/where is the process of "someone requesting friendship".

  • Initially would be notifications that appear on the same screen. The app process is as follows, I register with fb, I can add people who are registered, so I have a list of people. After I list these people I can add a person and have a friendship with her. At that time the requested person shall receive a notification.

  • I suppose what you want is for the app running on your phone to send a notification to the app running on another phone. If that is so you should use the service Google Cloud Messaging GCM. Behold here a tutorial.

  • Another possibility is to use the Parse

2 answers

3

The ideal is to use a service using an Intentservice that checks from time to time the need to display the notification, is simple and practical. When I used my app I checked data on a Webapi to then display the notification.

package servicos;

import android.app.IntentService;
import android.content.Intent;

public class ServicoNotificacaoWebApi extends IntentService {

    private long plngIntervaloVerificacao;
    private boolean pblnServicoAtivo;

    /**
     * Construtor
     */
    public ServicoNotificacaoWebApi() {
        super("ServicoNotificacao");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        pblnServicoAtivo = true;

        // Multiplicar por 1000, pois é em milisegundos
        plngIntervaloVerificacao = (intent.getLongExtra("INTERVALO_VERIFICACAO", 300)) * 1000;

        while (pblnServicoAtivo) {
            ConsultarWebApi();
        } 
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Ao encerrar o serviço, altera o flag para a thread parar
        pblnServicoAtivo = false;
    }

    /**
     * Verifica no web service se existem 
     * ordens de serviços disponíveis para a equipe
     */
    private void ConsultarWebApi() {
        try {

            // Tempo de espera até a próxima verificação no webapi
            Thread.sleep(plngIntervaloVerificacao); 

            if (!pblnServicoAtivo) {
                return;
            }

            // Não vou colocar o que eu faço para verificar a API para não ficar extenso, mais neste ponto eu exibo a notificação e no meu caso eu executo uma chamada para a tela de login de minha aplicação.
            if (WEBAPI_OK)
            ExibirNotificacao(this, "WEB_API", "Notificacao WebApi", 
                    "Mensagem", R.drawable.ic_launcher, 
                    9999, new Intent(this, ActLogin.class));

        } catch (Exception e) {
            // Caso seja necessário, colocar para gravar o log aqui
        }
    }

        /**
     * Exibe uma notificação
     * 
     * @param ctxContexto Contexto
     * @param strTituloNotificacao Título da notificação
     * @param strTituloMensagem Título da mensagem da notificação
     * @param strMensagem Mensagem
     * @param intIcone Ícone da notificação
     * @param intId Id da notificação (Necessário para cancelá-la)
     * @param intent Intent a ser disparada pela notificação
     */
    private void ExibirNotificacao(Context ctxContexto, String strTituloNotificacao, 
            String strTituloMensagem, String strMensagem, int intIcone, int intId, Intent intent) {

        NotificationManager notificationManager = (NotificationManager) 
                ctxContexto.getSystemService(Activity.NOTIFICATION_SERVICE);

        Notification notification = new Notification(intIcone, strTituloNotificacao, System.currentTimeMillis());

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
                Intent.FLAG_ACTIVITY_SINGLE_TOP | 
                Intent.FLAG_ACTIVITY_NEW_TASK);

        notification.defaults |= Notification.DEFAULT_SOUND; // Som padrão da notificação
        notification.flags = Notification.FLAG_AUTO_CANCEL; // Cancela a notificação no clique 

        PendingIntent pendingIntent = PendingIntent.getActivity(ctxContexto, 0, intent, 0);

        notification.contentIntent = pendingIntent;

        notification.setLatestEventInfo(ctxContexto, strTituloMensagem, strMensagem, pendingIntent);
        notificationManager.notify(9999, notification);
    }
}

In order to be called this Intentservice must be added to the Manifest.xml of your application:

<service
            android:name="servicos.ServicoNotificacaoWebApi"
            android:exported="false"
            android:process="servicos.ServicoNotificacaoWebApi" >
            <intent-filter>
                <action android:name="SERVICO_NOTIFICACAO_WEB_API" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
 </service>

And when it comes to calling, just call Intent with the name Voce put in Manifest.xml:

Intent lintentServico = new Intent("SERVICO_NOTIFICACAO_OS_AVULSA");        lintentServico.putExtra("INTERVALO_VERIFICACAO", 1);

// Inicia o serviço de notificação
pctxContexto.startService(lintentServico);
  • I’m not sure if this answers the question. Whether you answer it or not is a bad example of using a service. In this type of situation an Alarmmanager should be used to manage when checking the need to launch the notification along with a Broadcastreceiver, to launch the notification.

  • I was not aware of this type of implementation, although I have already used Broadcastreceiver. I believe that this does not justify giving -1, if you have a better answer, publish it.

  • I cannot answer because the question is not clear.

  • If you cannot answer, ok, then giving -1 for an implementation other than yours is not valid. We’re not in a competition, we want to help the community.

  • 1

    Don’t take this the -1, it’s not personal, I just evaluated your response and I think that such implementation is wrong considering the way Android works. You may not agree but negative answers or questions is also helping the community

  • 3

    Leaving aside the issue of -1, checking a server from time to time incurs unnecessary consumption of band and drums and is not the best way to do. For that there are the push Notifications that warn the application that there is something new on the server, including having the feature to start the application if it is not running. In the case of Android seek to know the Google Cloud Messaging as @ramaral has already quoted.

  • Here’s something I didn’t know... I’m waiting for the @ramaral answer, because, I don’t know this feature and it certainly makes sense this question of the consumption of band and drums. Thanks for the explanation Piovezan.

  • 3

    The question is too broad to answer, it would be too long. If you want to know more about the Parse and the Google Cloud Messaging(GCM) follow the links in my comments to the question. Alarmmanager is provided by the SDK to prevent each application, which needs to schedule tasks, from having to create its own service. If there is only one service, which can be used by any application, the necessary amount of resources (memory, processor, battery, etc.) necessary to perform this task is reduced.

  • 3

    The same applies to GSM. Think what it would be like if each application, which needed to communicate with an external service to obtain any kind of feedback, had its own service running on the same device.

Show 4 more comments

0

Hello, I was having the same problem and after a long time searching for the answer and testing I managed using Alarmmanager and Broadcastreceiver, what I needed: I have a web system where someone registers notifications in the database, and an API that returns a json with the requests, I needed something to run with the app open or closed checking for new messages and notifying the user.

Man Androidmanifest.xml

<receiver
        android:name=".Servico.BootReciever"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="ALARME_DISPARADO2"/>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

In my onCreate of Activity

boolean alarmeativo = (PendingIntent.getBroadcast( this, 0, new Intent( "ALARME_DISPARADO2" ), PendingIntent.FLAG_NO_CREATE ) == null);

        if(alarmeativo) {
            Intent intent = new Intent( "ALARME_DISPARADO2" );
            PendingIntent p = PendingIntent.getBroadcast( this, 0, intent, 0 );
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis( System.currentTimeMillis() );
            c.add( Calendar.SECOND, 3 );

            AlarmManager alarm = (AlarmManager) getSystemService( ALARM_SERVICE );
            alarm.set( AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), p );
        }

I check if the alarm is already created, assign the Intent that will be executed referencing my Broadcastreceiver, assign a time to start and configure the RTC_WAKEUP alarm to run even with the blogged device, done this in Broadcastrece start a Task, because I need to post on a web page, using recursiveness to continue executing.

Man Bootreciever.java

public class BootReciever extends BroadcastReceiver {
public static Usuario us;
public static Notifi not;
public static NotifiSetor notSet;
public static Agenda notAg;

public static boolean Iniciar = true;
public static boolean saida;

int x = 0;

@Override
public void onReceive(Context context, Intent intent) {

        Iniciar = false;
        Usuario u = new Usuario( context );
        u.Select();
        us = u;

        Notifi n = new Notifi( context );
        not = n;

        NotifiSetor ns = new NotifiSetor(context );
        notSet = ns;

        Agenda ag = new Agenda( context );
        notAg = ag;

        NotificationTask us = new NotificationTask();
        us.execute(context);
}

public boolean isOnline(Context context) {
    boolean conectado;
    try {
        ConnectivityManager conectivtyManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
        if (conectivtyManager.getActiveNetworkInfo() != null
                && conectivtyManager.getActiveNetworkInfo().isAvailable()
                && conectivtyManager.getActiveNetworkInfo().isConnected()) {
            conectado = true;
        } else {
            conectado = false;
        }
    } catch (Exception e) {
        conectado = false;
    }
    return conectado;
}

private class NotificationTask extends AsyncTask<Context, Void, Context> {
    @Override
    protected Context doInBackground(Context... ct) {


        saida = false;
        try {
            Agenda a = new Agenda(notAg.getCt());
            List<Agenda> list = a.SelectExibir();
            if(list != null) {
                for (int x = 0; x < list.size(); x++) {
                    long date1 = System.currentTimeMillis();
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                    String dateString = sdf.format(date1);
                    if(list.get(x).getExibir().equals(dateString)) {
                        Calendar cal = Calendar.getInstance( TimeZone.getTimeZone("GMT"));
                        Date currentLocalTime = cal.getTime();
                        DateFormat date = new SimpleDateFormat("dd-MM-yyyy");
                        date.setTimeZone(TimeZone.getTimeZone("GMT"));
                        String localTime = date.format(currentLocalTime);

                        NewMessageNotification.notify(ct[0], list.get(x).getTitulo(), list.get(x).getMensagem(), list.get(x).getID());
                        a.setID(list.get(x).getID());
                        a.setUltimo_Exib(localTime);
                        a.UpdateExibir();
                    }
                }
            }
        } catch (Exception e) {
        }

        if(isOnline(ct[0])) {
            //Log.d("",String.valueOf( x++ ));
            // notificaçoes agendadas
            try {
                //buscar na api
                // buscar no webservice
                String json = "json a ser enviando para API";
                HttpService servi = new HttpService();
                String retorno = servi.post(json);

                try {
                    JSONObject jsonObj = new JSONObject(retorno);
                    JSONArray array = jsonObj.getJSONArray("Res");
                    if (jsonObj.getBoolean("Response")) {

                        for (int i = 0; i < array.length(); i++) {
                            // notificacao
                            notAg.setID(array.getJSONObject(i).getInt("ID"));
                            if (!notAg.ValidaId()) {
                                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
                                //cal.add(Calendar.DAY_OF_MONTH, -1);
                                Date currentLocalTime = cal.getTime();
                                DateFormat date = new SimpleDateFormat("dd-MM-yyyy");
                                date.setTimeZone(TimeZone.getTimeZone("GMT"));
                                String localTime = date.format(currentLocalTime);

                                notAg.setTitulo(array.getJSONObject(i).getString("TITULO"));
                                notAg.setMensagem(array.getJSONObject(i).getString("MENSAGEM"));
                                notAg.setCadastro(array.getJSONObject(i).getString("DATA_CAD"));
                                notAg.setExibir(array.getJSONObject(i).getString("REPETIR"));
                                notAg.setUltimo_Exib(localTime);
                                notAg.setStatus(array.getJSONObject(i).getInt("STATUS"));
                                notAg.Insert();
                            } else {
                                notAg.setTitulo(array.getJSONObject(i).getString("TITULO"));
                                notAg.setMensagem(array.getJSONObject(i).getString("MENSAGEM"));
                                notAg.setCadastro(array.getJSONObject(i).getString("DATA_CAD"));
                                notAg.setExibir(array.getJSONObject(i).getString("REPETIR"));
                                notAg.setStatus(array.getJSONObject(i).getInt("STATUS"));
                                notAg.Update();
                            }
                        }
                    }
                } catch (Exception e) {
                }
            } catch (Exception e) {
                // Restore interrupt status.
                //Thread.currentThread().interrupt();
            }

            // notificaçoes geral equipe
            try {
                //buscar na api
                // buscar no webservice
                String json = "json a ser enviando para API";
                HttpService servi = new HttpService();
                String retorno = servi.post(json);

                try {
                    JSONObject jsonObj = new JSONObject(retorno);
                    JSONArray array = jsonObj.getJSONArray("Res");
                    if (jsonObj.getBoolean("Response")) {

                        for (int i = 0; i < array.length(); i++) {
                            // notificacao
                            not.setID(array.getJSONObject(i).getInt("ID"));
                            if (!not.ValidaId()) {
                                not.setTitulo(array.getJSONObject(i).getString("TITULO"));
                                not.setMensagem(array.getJSONObject(i).getString("MENSAGEM"));
                                not.setData(array.getJSONObject(i).getString("DATA_CAD"));
                                not.setStatus(array.getJSONObject(i).getInt("STATUS"));
                                not.Insert();
                                NewMessageNotification.notify(ct[0], not.getTitulo(), not.getMensagem(), not.getID());
                            }
                        }
                    }
                } catch (Exception e) {
                }
            } catch (Exception e) {
                // Restore interrupt status.
                //Thread.currentThread().interrupt();
            }

            // notificaçoes geral setor
            try {
                //buscar na api
                // buscar no webservice
                String json = "json a ser enviando para API";
                HttpService servi = new HttpService();
                String retorno = servi.post(json);

                try {
                    JSONObject jsonObj = new JSONObject(retorno);
                    JSONArray array = jsonObj.getJSONArray("Res");
                    if (jsonObj.getBoolean("Response")) {

                        for (int i = 0; i < array.length(); i++) {
                            // notificacao
                            notSet.setID(array.getJSONObject(i).getInt("ID"));
                            if (!notSet.ValidaId()) {
                                notSet.setTitulo(array.getJSONObject(i).getString("TITULO"));
                                notSet.setMensagem(array.getJSONObject(i).getString("MENSAGEM"));
                                notSet.setData(array.getJSONObject(i).getString("DATA_CAD"));
                                notSet.setStatus(array.getJSONObject(i).getInt("STATUS"));
                                notSet.Insert();
                                NewMessageNotification.notify(ct[0], notSet.getTitulo(), notSet.getMensagem(), notSet.getID());
                            }
                        }
                    }
                } catch (Exception e) {
                }
                // exibir
            } catch (Exception e) {
                // Restore interrupt status.
                //Thread.currentThread().interrupt();
            }
        }
        try { 
            // recursividade para continuar executando
            doInBackground( ct[0] );
        } catch(Exception e) {

        }
        return ct[0];
    }

    @Override
    protected void onPostExecute(Context result) {
        // Após a inserção da nota, vamos mostrar um Toast ao usuário
        saida = true;
        Iniciar = true;
        doInBackground(result);
    }
}

}

Upshot I/art: Increasing code cache Capacity to 128KB
D/14:46:36: -> Initiated
D/14:46:41: -> Initiated
D/14:46:42: -> Initiated
D/14:46:44: -> Initiated
D/14:46:45: -> Initiated
D/14:46:46: -> Initiated
D/14:46:48: -> Initiated
D/14:46:49: -> Initiated
D/14:46:50: -> Initiated
D/14:46:52: -> Initiated
D/14:46:53: -> Initiated
D/14:46:54: -> Initiated
D/14:46:56: -> Initiated
D/14:46:56: -> Initiated
D/14:46:57: -> Initiated
D/14:46:58: -> Initiated
D/14:46:59: -> Initiated
D/14:47:00: -> Started
D/14:47:01: -> Initiated
D/14:47:03: -> Initiated
D/14:47:04: -> Initiated
D/14:47:07: -> Initiated
D/14:47:09: -> Initiated
D/14:47:11: -> Initiated
D/14:47:12: -> Initiated
D/14:47:15: -> Initiated
D/14:47:16: -> Initiated
D/14:47:17: -> Initiated
D/14:47:18: -> Initiated
D/14:47:19: -> Initiated
D/14:47:20: -> Initiated
D/14:47:21: -> Initiated
D/14:47:22: -> Initiated
D/14:47:23: -> Initiated
D/14:47:24: -> Initiated
D/14:47:25: -> Initiated
D/14:47:26: -> Initiated
D/14:47:27: -> Initiated
D/14:47:28: -> Initiated
D/14:47:30: -> Initiated
D/14:47:32: -> Initiated
D/14:47:33: -> Initiated
D/14:47:34: -> Initiated
D/14:47:35: -> Initiated
D/14:47:36: -> Initiated
D/14:47:37: -> Initiated
D/14:47:38: -> Initiated
D/14:47:38: -> Initiated
D/14:47:39: -> Initiated
D/14:47:40: -> Initiated
D/14:47:41: -> Initiated
D/14:47:42: -> Initiated
D/14:47:43: -> Initiated
D/14:47:43: -> Initiated
D/14:47:44: -> Initiated
D/14:47:45: -> Initiated
D/14:47:46: -> Initiated
D/14:47:46: -> Initiated
D/14:47:47: -> Initiated
D/14:47:48: -> Initiated
D/14:47:49: -> Initiated
D/14:47:50: -> Initiated
I/art: Background Sticky Concurrent mark Sweep GC Freed 3085(212KB) Allocspace Objects, 2(40KB) LOS Objects, 1% free, 28MB/28MB, paused 5.805ms total 16.525ms
D/14:47:50: -> Initiated
D/14:47:51: -> Initiated
D/14:47:52: -> Initiated
D/14:47:53: -> Initiated
D/14:47:54: -> Initiated
D/14:47:55: -> Initiated
D/14:47:56: -> Initiated
D/14:47:57: -> Initiated
D/14:47:58: -> Initiated
D/14:47:58: -> Initiated
D/14:47:59: -> Initiated
D/14:48:00: -> Started
D/14:48:01: -> Started
D/14:48:02: -> Initiated
D/14:48:02: -> Initiated
D/14:48:03: -> Started
D/14:48:04: -> Initiated
D/14:48:05: -> Initiated
D/14:48:06: -> Initiated
D/14:48:07: -> Initiated
D/14:48:09: -> Initiated
D/14:48:10: -> Initiated
D/14:48:11: -> Initiated
D/14:48:12: -> Initiated
D/14:48:13: -> Initiated
D/14:48:13: -> Initiated
D/14:48:14: -> Initiated
D/14:48:15: -> Initiated
D/14:48:16: -> Initiated
D/14:48:17: -> Initiated
D/14:48:18: -> Initiated
D/14:48:19: -> Initiated
D/14:48:20: -> Initiated
D/14:48:21: -> Initiated
D/14:48:22: -> Initiated
D/14:48:22: -> Initiated
Application terminated.

And testing on my mobile worked properly and with little delay time to display notifications with the application closed and open, you can also call a Service or an Intetservice on onReceive.

  • 2

    Greetings to you, Rafael. You have published exactly this answer here: https://answall.com/a/305514/5878. If an answer to another question answers this, then signal as duplicate, do not post the same answer over and over again. Duplicate content only pollutes the community.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.