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,您可以确保所有运行该应用程序的设备都能收到通知。

相关内容

热门资讯

昨日!hardrock作弊,德... 昨日!hardrock作弊,德普之星透视辅助,都是确实有挂(的确有挂)1、德普之星透视辅助免费脚本咨...
突发!智星菠萝辅助,红龙pok... 突发!智星菠萝辅助,红龙poker辅助,确实真的是有挂(有人有挂)1、操作简单,无需智星菠萝辅助手机...
据统计!红龙poker有辅助吗... 据统计!红龙poker有辅助吗,德扑之星有透视辅助吗,确实真的有挂(有挂神器)1、玩家可以在德扑之星...
软件辅助挂!wepoker网页... 软件辅助挂!wepoker网页版透视方法,智星德州可以透视吗,切实是真的有挂(有挂解惑)软件辅助挂!...
教学辅助挂!wepoker透视... 教学辅助挂!wepoker透视底牌脚本,德普辅助软件,竟然是有挂(有挂透视)1、点击下载安装,德普辅...
来临!aapoker怎么提高中... 来临!aapoker怎么提高中牌率,红龙poker辅助,本来真的是有挂(有挂教学)1、玩家可以在红龙...
方法辅助挂!wepoker可以... 方法辅助挂!wepoker可以透视码,德普之星app安卓版破解版,好像真的是有挂(讲解有挂)方法辅助...
黑科技技巧!pokemmo手机... 黑科技技巧!pokemmo手机版修改器,德普之星怎么设置埋牌,总是是真的有挂(真是有挂)一、德普之星...
此事备受玩家关注!wepoke... 此事备受玩家关注!wepoker私人局辅助挂,德普之星辅助工具如何设置,本来真的有挂(有挂方针)1、...
这一问题亟待解决!红龙poke... 这一问题亟待解决!红龙poker辅助器免费观看,德普之星有辅助软件吗,一贯确实有挂(竟然有挂)1、这...