当应用程序在后台时无法从通知启动活动

时间:2021-01-12 18:30:32

标签: android firebase-cloud-messaging

我使用以下代码在用户点击通知时显示通知并启动活动。当应用程序处于前台时,一切都按预期工作。即当用户点击通知时,指定的活动将与所有活动的后退堆栈一起显示。 但是当应用在后台或被杀死时,点击通知不会打开指定的活动,它会重新运行应用并启动启动器活动。

请帮忙!

这是我的 NotificationHelper 类:


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.provider.Settings;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.app.TaskStackBuilder;

import java.util.Date;


public class NotificationHelper {
    public static final String CH_ID="zsms001";
    public static final String CH_NAME="zenotek sms";
    public static final String CH_DESC="Zenotek SMS Notifications";
    private static int rCode=(int) new Date().getTime();

    public static void displayNotification(Context context, String mtitle, String mbody){
        Intent intent;

        if (mtitle.equals("New Homework")){
            intent=new Intent(context, HomeworkActivity.class);
        }
        else {
            if (mtitle.equals("New Circular")){
                intent=new Intent(context, CircularActivity.class);
            }
            else {
                intent=new Intent(context, NavigationActivity.class);
            }
        }

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(NavigationActivity.class);
        stackBuilder.addNextIntent(intent);
        PendingIntent pintent = PendingIntent.getActivity(context, rCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder nBuilder=new NotificationCompat.Builder(context,CH_ID)
                .setSmallIcon(R.drawable.ic_ghs_logo_small)
                .setContentTitle(mtitle)
                .setContentText(mbody)
                .setContentIntent(pintent)
                .setAutoCancel(true)
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setPriority(Notification.PRIORITY_DEFAULT)
                .setLights(Color.RED,1000,2000);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationManager nMan;

            NotificationChannel nChannel =new NotificationChannel(CH_ID,CH_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            nChannel.setDescription(CH_DESC);
            nChannel.enableLights(true);
            nChannel.setLightColor(Color.RED);

            nMan=context.getSystemService(NotificationManager.class);
            assert nMan != null;
            nBuilder.setChannelId(CH_ID);
            nMan.createNotificationChannel(nChannel);
            nMan.notify(rCode,nBuilder.build());
        }
        else {
            NotificationManagerCompat nMan;
            nMan=NotificationManagerCompat.from(context);
            nMan.notify(rCode,nBuilder.build());
        }
    }
}

FirebaseMsgService 类:

package com.zenotek.ghsvaranasi;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import org.json.JSONException;
import org.json.JSONObject;

public class FirebaseMsgService extends FirebaseMessagingService {
    private FirebaseAuth mAuth = FirebaseAuth.getInstance();
    private int cuid;
    public static boolean NewTokenGenerated=false;

    @Override
    public void onNewToken(@NonNull String s) {
        Log.d("New Token",s);
        if (mAuth.getCurrentUser()!=null){
            Log.d("Current user",mAuth.getCurrentUser().getUid());
            cuid=Integer.parseInt(mAuth.getCurrentUser().getUid().substring(1));
            SaveTokentoServer savetoken=new SaveTokentoServer();
            savetoken.execute(s);
        }
        else{
            NewTokenGenerated=true;
        }
    }

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

        if (remoteMessage.getNotification()!=null){
            String mTitle=remoteMessage.getNotification().getTitle();
            String mBody=remoteMessage.getNotification().getBody();

            NotificationHelper.displayNotification(getApplicationContext(), mTitle, mBody);
        }
    }

    public class SaveTokentoServer extends AsyncTask<String,String,String> {
        String msg;

        @Override
        protected String doInBackground(String... strings) {
            String ftoken=strings[0];
            RestAPI api=new RestAPI();

            try {
                JSONObject joRoot=api.Save_SFirebase_Token(cuid,ftoken);
                Log.d("Save Token joRoot",joRoot.toString());
                boolean RStat=joRoot.getBoolean("Successful");

                if (!RStat){
                    msg=joRoot.getString("ErrorMessage");
                    Log.d("save token joRoot Error",msg);
                }
                else {
                    Log.d("save token joRoot","Token Refreshed Successfully!");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

首先,您需要从 FirebaseMessagingService 扩展您的类。下面是一个实现示例:https://gist.github.com/jirawatee/85d4b46a89b9ae821b63c31f5d5189de

此外,如果您想在后台处理通知,则需要使用“数据”而不是“通知”发送通知

https://firebase.google.com/docs/cloud-messaging/android/receive