Android Java应用程序 - 当发送通知时,发送者能收到通知,但其他运行该应用程序的设备却收不到。
创始人
2024-08-14 08:00:07
0

要解决这个问题,您可以使用Firebase Cloud Messaging(FCM)来发送通知,以便所有设备都能收到通知。以下是一个示例代码,演示了如何使用FCM发送通知:

  1. 在您的项目中添加Firebase依赖项。在项目的 build.gradle 文件中添加以下代码:
dependencies {
    implementation 'com.google.firebase:firebase-messaging:20.0.0'
}
  1. 创建一个名为 MyFirebaseMessagingService 的类,扩展自 FirebaseMessagingService。重写 onMessageReceived 方法来处理接收到的通知。
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMessagingService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            // 在这里处理接收到的通知
        }
    }
}
  1. AndroidManifest.xml 文件中注册 MyFirebaseMessagingService


    

        
            
                
            
        

        

    


  1. 在您的代码中发送通知。您可以使用以下代码示例发送通知:
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.RemoteMessage;

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

        // 在这里发送通知
        sendNotification("Hello, World!");
    }

    private void sendNotification(String message) {
        FirebaseMessaging.getInstance().send(new RemoteMessage.Builder("YOUR_SENDER_ID" + "@gcm.googleapis.com")
                .setMessageId(Integer.toString(getRandomId()))
                .addData("message", message)
                .build());
    }

    private int getRandomId() {
        return new Random().nextInt(10000);
    }
}

以上代码示例了如何使用Firebase Cloud Messaging发送通知。确保在 YOUR_SENDER_ID 处替换为您的 Firebase 项目的 Sender ID。

通过使用FCM,您可以确保所有运行该应用程序的设备都能收到通知。

相关内容

热门资讯

此事引发网友热议!免费广东雀神... 此事引发网友热议!免费广东雀神智能插件安装,广西八一字牌可以破解吗,练习教程(一直确实有挂)-哔哩哔...
更值得关注的是!吉祥填大坑的破... 更值得关注的是!吉祥填大坑的破解方法,同城乐吧乐享版510k辅助,绝活儿教程(一直确实有挂的)-哔哩...
为切实保障!微信小程序微乐辅助... 为切实保障!微信小程序微乐辅助器,久久互娱科技,步骤教程(其实是真的有挂)-哔哩哔哩所有人都在同一条...
据了解!广西八一字牌可以破解码... 据了解!广西八一字牌可以破解码,新天道辅助脚本,方针教程(果然是有挂)-哔哩哔哩;1、金币登录送、破...
近年来!来玩app辅助器,天天... 近年来!来玩app辅助器,天天乐卡五星,攻略教程(一贯是真的有挂的)-哔哩哔哩1、游戏颠覆性的策略玩...
突发!约局吧脚本有用吗,玩吧辅... 突发!约局吧脚本有用吗,玩吧辅助脚本,指南书教程(果然是真的有挂)-哔哩哔哩该软件可以轻松地帮助玩家...
刚刚!陕麻圈延安划水辅助,爱玩... 刚刚!陕麻圈延安划水辅助,爱玩娱乐暗堡辅助,经验教程(其实是有挂的)-哔哩哔哩;1、金币登录送、破产...
刚刚!辅助定制交易平台,杭州都... 刚刚!辅助定制交易平台,杭州都莱辅助软件,法门教程(果然是有挂的)-哔哩哔哩1、杭州都莱辅助软件系统...
据报道!川南休闲辅助,休闲九九... 据报道!川南休闲辅助,休闲九九破解版,机巧教程(其实确实有挂的)-哔哩哔哩休闲九九破解版是一种具有地...
出现新变化!九游辅助插件,四川... 出现新变化!九游辅助插件,四川游戏家园通用辅助,诀窍教程(一贯是有挂的)-哔哩哔哩1、完成四川游戏家...