【问题标题】:Unable to launch activity from notification when app is in background当应用程序处于后台时,无法从通知中启动活动
【发布时间】:2021-01-12 18:30:32
【问题描述】:

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

请帮忙!

这是我的 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;
        }
    }
}

【问题讨论】:

    标签: android firebase-cloud-messaging


    【解决方案1】:

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

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

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

    【讨论】:

    • 我已经有一个扩展 FirebaseMessagingService 的类。我在原始帖子中附加了代码,请建议我是否必须对其进行任何更改。此外,正如您所建议的,我已在通知中包含数据有效负载,但我无法理解当用户点击通知时我将如何使用该数据来启动活动。
    • 当您发送带有数据的通知时,Android系统会自动调用onMessageReceived函数。因此,如果您在 onMessageReceived 中编写意图,用户将在他/她单击通知时启动活动。 medium.com/@mohitdholakia4/…
    • 我刚刚从您的第二个链接 (firebase.google.com/docs/cloud-messaging/android/receive) 中得到了我的问题的答案,该链接说:“数据有效负载是在您的启动器 Activity 的意图中提供的。”非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2020-04-25
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多