应用程序被杀后推送通知

时间:2021-09-15 01:35:39

I can't seem to receive FCM Push Notifications that I send from the FCM console after app is killed on android, as in long-press the Overview button and swiping the app to be killed. It works absolutely fine when the app is running in the foreground or background. This may seem like a duplicate question but I have tried the other methods but I still cannot seem to get it.

我似乎无法接收我在Android上杀死应用程序后从FCM控制台发送的FCM推送通知,如长按概述按钮并轻扫要杀死的应用程序。当应用程序在前台或后台运行时,它可以正常工作。这似乎是一个重复的问题,但我尝试了其他方法,但我似乎仍然无法得到它。

NotificationService.java

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

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

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());


}

}

3 个解决方案

#1


0  

Try adding BroadcastReceiver to your MainActivity.java

尝试将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();
    }
}

#2


0  

I had exactly the same problem. Notifications showed just fine in foreground and background mode, but not when the app was killed. Eventually I found this: https://github.com/firebase/quickstart-android/issues/41#issuecomment-306066751

我有完全相同的问题。通知在前台和后台模式中表现得很好,但在应用程序被杀死时却没有。最终我发现了这个:https://github.com/firebase/quickstart-android/issues/41#issuecomment-306066751

The problem is with the debugging mode in Android Studio. To correctly test your notifications do the following: Run your app via debug in Android Studio. Swipe it away to be killed. Restart the app via the launcher icon on your phone. Swipe it away again (so it gets killed).

问题在于Android Studio中的调试模式。要正确测试您的通知,请执行以下操作:在Android Studio中通过调试运行您的应用。滑动即可将其杀死。通过手机上的启动器图标重新启动应用。再次滑动它(因此它被杀死)。

Send your notification and now you will see it!

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

Hope this solved your problem.

希望这能解决你的问题。

#3


-1  

Try Change the Flag

尝试更改标志

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

#1


0  

Try adding BroadcastReceiver to your MainActivity.java

尝试将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();
    }
}

#2


0  

I had exactly the same problem. Notifications showed just fine in foreground and background mode, but not when the app was killed. Eventually I found this: https://github.com/firebase/quickstart-android/issues/41#issuecomment-306066751

我有完全相同的问题。通知在前台和后台模式中表现得很好,但在应用程序被杀死时却没有。最终我发现了这个:https://github.com/firebase/quickstart-android/issues/41#issuecomment-306066751

The problem is with the debugging mode in Android Studio. To correctly test your notifications do the following: Run your app via debug in Android Studio. Swipe it away to be killed. Restart the app via the launcher icon on your phone. Swipe it away again (so it gets killed).

问题在于Android Studio中的调试模式。要正确测试您的通知,请执行以下操作:在Android Studio中通过调试运行您的应用。滑动即可将其杀死。通过手机上的启动器图标重新启动应用。再次滑动它(因此它被杀死)。

Send your notification and now you will see it!

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

Hope this solved your problem.

希望这能解决你的问题。

#3


-1  

Try Change the Flag

尝试更改标志

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