首页 > 解决方案 > 为什么当我的应用程序关闭时我没有收到 FCM 通知?

问题描述

我正在从 Rest Api 发送通知。但这仅在我的应用程序处于前台和后台时才有效。但是当我关闭我的应用程序时。我在三星测试了我的应用程序。它不起作用。我正在使用 FCM。我的 FirebaseMessangingService 类如下:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        System.out.println("From: " + remoteMessage.getFrom());
        if (remoteMessage == null)
            return;
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
            try {
                System.out.println(remoteMessage.getData().get("title"));
                JSONObject json = new JSONObject(remoteMessage.getData());
                handleDataMessage(json);
                //showNotification(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

    private void handleDataMessage(JSONObject json) throws Exception {
        System.out.println("Json:"+json);
        showNotification(json.getString("title"),json.getString("body"));
    }

    private void showNotification(String title,String message){
        System.out.println("Message:"+message);
        Intent notificationIntent=new Intent(this, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent= PendingIntent.getActivity(this,0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder= new NotificationCompat.Builder(getBaseContext(), "myNotificationChannel")
                .setAutoCancel(true)
                .setSound(sound)
                .setContentTitle(title)
                .setVibrate(new long[]{1000,1000,1000,1000})
                .setContentText(message)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationManagerCompat.IMPORTANCE_MAX)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
                .setColorized(true)
                .setColor(Color.RED)
                .setDefaults(DEFAULT_ALL);
        NotificationManager notificationManager= (NotificationManager) getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(100,builder.build());
    }

    @Override
    public void onNewToken(@NonNull String s) {
        System.out.println("New Token:"+s);
        super.onNewToken(s);
    }
}

我的 Rest Api 代码如下:

{
  "to":"/topics/weather",
  "data": {
    "title":"Hello Guys ",
    "body":"How are you?"
  }
}

我的清单在这里:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lastnotification">
 <uses-permission android:name="android.permission.INTERNET" /> 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                      <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
    </application>

</manifest>

我的 MainActivity 代码如下:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirebaseMessaging.getInstance().subscribeToTopic("weather")
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        String msg="Subscribed Succesfully";
                        if (!task.isSuccessful()) {
                            msg="Subscribe Failed";
                        }
                        Log.d(TAG, msg);
                        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

标签: androidfirebasefirebase-cloud-messagingandroid-notifications

解决方案


推荐阅读