Android Studio, push notifications are not received when app is closed or suspended

0

I have an application that uses firebase to send push notifications
What happens is that in my code I have several conditions when the title is a specific word do something, only when the app is closed or in the background only receives the predefined notification and does not access the condition I have, instead if it is open normally and it shows me a notification depending on what the title says, I leave the code where I have implemented

MiFirebaseMessagingService.java

package com.exaple.eduardo.hola.firebase;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

import com.exaple.eduardo.hola.BaseDeDatos;
import com.exaple.eduardo.hola.Frase_del_Dia;
import com.exaple.eduardo.hola.MainActivity;
import com.exaple.eduardo.hola.R;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Map;

public class MiFirebaseMessagingService extends FirebaseMessagingService {


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    if (remoteMessage.getNotification() != null){


        mostrarNotificacion(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(),remoteMessage.getData());

    }


}

private void mostrarNotificacion(String title, String body, Map<String, String> data) {

    Uri sounduri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);


    if (title.equals("Frase")){

        BaseDeDatos db2 = new BaseDeDatos(this, "db", null, 1);
        db2.openDataBase();
        final SQLiteDatabase BaseDeDataBase = db2.getWritableDatabase();
        int numero = (int) (Math.random() * 70) + 1;
        Cursor file = BaseDeDataBase.rawQuery("select frase from Frases where id="+ numero,null);

        Intent intent = new Intent(this, Frase_del_Dia.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("numero", numero);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);


        if (file.moveToFirst()){
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.icov2)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setContentTitle("Frase del dia")
                    .setContentText(file.getString(0))
                    .setAutoCancel(true)
                    .setSound(sounduri)
                    .setContentIntent(pendingIntent);


            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notificationBuilder.build());
        }
        BaseDeDataBase.close();

    }
    else {

        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.icov2)
                .setTicker("Nuevo Mensaje")
                .setPriority(Notification.PRIORITY_HIGH)
                .setContentTitle(title)
                .setContentText(body)
                .setAutoCancel(true)
                .setSound(sounduri)
                .setContentIntent(pendingIntent);


        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}

}

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="false"
    android:icon="@mipmap/ico"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/icov2"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="GoogleAppIndexingWarning">
    <activity
        android:name=".MainActivity"
        android:theme="@style/SplashTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".firebase.MiFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service android:name=".firebase.MiFirebaseInstanceidService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <service
        android:name=".service.MusicService"
        android:enabled="true"
        android:exported="true"
        tools:ignore="ExportedService">
        <intent-filter>
            <action android:name="android.media.browse.MediaBrowserService" />
        </intent-filter>
    </service>

    <receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>

    <activity android:name=".MenuPrincipal" />
    <activity android:name=".Frase_del_Dia" />
    <activity android:name=".ProximamenteActivity" />
    <activity android:name=".TeAmoActivity" />
    <activity android:name=".Notificaciones"></activity>
</application>

    
asked by Eduardo Prieto Campos 05.11.2018 в 20:39
source

1 answer

0

Maybe my solution does not fit your code but it could be helpful for you, I can do it in the following way, just add in your AndroidManifest:

     <meta-data
             android:name="com.google.firebase.messaging.default_notification_icon            
android:resource="@drawable/ic_bell" /> 

Create a new activity, which will be your activity to be launched by default, for example for me it is PushNotificationsActivity.java (it will open when clicking on the push in the notification bar):

....

      <activity
                android:name=".firebase.notifications.PushNotificationsActivity"
                android:label="@string/app_name"
                android:theme="@style/AppTheme.NoActionBar">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
...

Now, I see that you are saving in a database in case of a push type "Phrase", here I leave something similar, I keep the push in my DB to display it later in CardView, but I leave the part in which the push data is received, in your PushNotificationsActivity.java

.....
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Toast.makeText(this, TAG, Toast.LENGTH_SHORT).show();
        setContentView(R.layout.activity_notifications);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle(getString(R.string.title_activity_notifications));

        if (getIntent().getExtras() != null){
           /// getIntent().getExtras().keySet() --------AQUI OBTIENES LA PUSH Y PUEDES HACER LO QUE NECESITES, EN MI CASO ALMACENO MI PUSH EN LA BASE DE DATOS--------
            for (String key : getIntent().getExtras().keySet()){
                if (key.equals("idPush")){
                    OperacionesDB.Pushs.setPush(new Push(Integer.parseInt(getIntent().getExtras().getString("idPush")),
                            getIntent().getExtras().getString("titulo"), getIntent().getExtras().getString("descripcion"),
                            getIntent().getExtras().getString("fecha"), getIntent().getExtras().getString("hora"),
                            Integer.parseInt(getIntent().getExtras().getString("tipo")), getIntent().getExtras().getString("estadoVisto"),
                            Integer.parseInt(getIntent().getExtras().getString("fkIdUserPush"))));
                    break;
                }
            }
        }
}
.....
    
answered by 07.11.2018 / 16:48
source