应用程序被杀死后的推送通知

13

我似乎无法在安卓设备上从FCM控制台发送的推送通知在应用程序被杀死后接收,例如长按总览按钮并将应用程序向左滑以使其关闭。但是当应用程序在前台或后台运行时,它完全正常工作。这可能看起来像是一个重复的问题,但我已经尝试了其他方法,但仍然无法解决。

NotificationService.java

public class NotificationService extends FirebaseMessagingService
{

private static final String TAG = "FCM Service";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
    sendNotification(remoteMessage.getNotification().getBody());
}

private void sendNotification(String messageBody) {

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

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        android.support.v4.app.NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
}
}

TokenRefresh.java

public class TokenRefresh extends FirebaseInstanceIdService {

private static final String TAG = "FirebaseIDService";

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.

}

}

主活动(MainActivity.java)

public class MainActivity extends AppCompatActivity {

Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    FirebaseMessaging.getInstance().subscribeToTopic("global");

    String token = ("fcm"+ FirebaseInstanceId.getInstance().getToken());


}

}

请看以下链接中的第一个答案 ;-) https://dev59.com/JVoU5IYBdhLWcg3wM08H 玩得开心 - Pouya Amirahmadi
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Darsshan
你能贴出堆栈信息吗? - AL.
I/System.out: FCM Token=================>fM46b47CX4Y:APA91bELK7Oejzf_C3IDd-xZrJcK930pg72AOJCK7OeR74zxjZZzKUcSmcn8X_KJLHglyp1VP5QVW33nbFjfczOSx5H2F-7vkpXWQ3W85I_CzQZYGTKOKC_IsVeM8EERaJxJpb4tKG6TW/dalvikvm: VFY:无法解析实例字段151I/FA: 未找到标签管理器,因此将不会使用它W/dalvikvm: threadid = 11:线程退出时出现未捕获的异常(group = 0x415aac80) I/Process:发送信号。 PID:28652 SIG:9 从目标VM断开连接,地址:'localhost:8608',传输:'socket' - Darsshan
4个回答

26

我曾经也遇到了同样的问题。通知在前台和后台模式下都正常显示,但在应用程序被杀死时却无法显示。最终我找到了解决方法:https://github.com/firebase/quickstart-android/issues/41#issuecomment-306066751

这个问题与Android Studio的调试模式有关。为了正确测试您的通知,请按以下步骤操作: 通过Android Studio中的调试运行应用程序。 将应用程序滑动关闭以结束它。 通过手机上的启动器图标重新启动应用程序。 再次将其滑动关闭(以使其被结束)。

发送您的通知,现在您将看到它!

希望这解决了您的问题。


如何在接收到推送通知后执行一些代码。例如,在通过 FCM 或 APNS 接收到已终止的 iOS 应用程序的推送通知后,向服务器回复一些数据? - Shubham1164
在此页面,您可以阅读有关接收推送消息(https://firebase.google.com/docs/cloud-messaging/android/receive)的内容。正如在此处所述,无论应用程序处于前台还是后台,数据消息都会在onMessageReceived中处理。如果您的应用程序被杀死并且用户点击通知,则会返回到应用程序。在我的MainActivity.java的onResume中,我检查了意图是否带有“url”(notificationUrl = getIntent().getStringExtra("url");),该意图随通知一起发送。如果是这样,我知道活动是通过单击通知打开的,并且我会对其进行处理。 - iDoes
我无法在IOS上完成它。 - Shubham1164
啊,非常抱歉。我误读了你的问题。我不知道它在iOS上如何工作,只知道在Android上。 - iDoes

2
您需要标记您的 Firebase 服务类,以便它不会与您的主应用程序一起被终止。
    ComponentName componentName = new ComponentName(
            applicationContext,
            FCMService.class);

    applicationContext.getPackageManager().setComponentEnabledSetting(
            componentName,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);

您可以 查看这个真实的Java实现


链接失效 - “404 | 页面未找到”。 - Pang

0

尝试将BroadcastReceiver添加到您的MainActivity.java

BroadcastReceiver mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);

                    displayFirebaseRegId();

                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");

                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();

                    txtMessage.setText(message);
                }
            }
        };

        displayFirebaseRegId();
    }

    // Fetches reg id from shared preferences
    // and displays on the screen
    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId))
            txtRegId.setText("Firebase Reg Id: " + regId);
        else
            txtRegId.setText("Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}

但是,当Firebase已经运行通知服务时,我该如何专门启动一个针对Firebase的服务呢? - Darsshan
我在清单文件中已经有这两个服务了:code <service android:name=".NotificationService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> code我还缺少什么? - Darsshan
此外,Firebase服务不是在启动时由Google Play服务启动的吗? - Darsshan
服务正常。尝试检查BroadcastReceiver。 - Smeet Hirekhan
据我所知,FCM不需要广播接收器。 - Darsshan
显示剩余2条评论

-5

尝试更改标志

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

3
这怎么能有帮助呢?这些通知来自 FCM 服务器,而不是您的应用程序生成的。没有机会创建一个意图。 - James Moore

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接