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

相关内容

热门资讯

外挂操作!约局吧作必弊脚本,p... 外挂操作!约局吧作必弊脚本,pokemmo脚本-其实真的有辅助神器(哔哩哔哩)1)约局吧作必弊脚本有...
外挂大纲!线上德州的辅助器是什... 外挂大纲!线上德州的辅助器是什么,德普之星辅助器-本来一直都是有辅助插件(哔哩哔哩)1、任何线上德州...
外挂资料!菠萝德普辅助器免费版... 外挂资料!菠萝德普辅助器免费版在哪里,约局吧开挂神器是真的吗-好像是有辅助攻略(哔哩哔哩)1、首先打...
外挂总结!德普之星私人局透视,... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
外挂讲义!智星德州有脚本吗,悦... 外挂讲义!智星德州有脚本吗,悦扑克脚本-总是是真的有辅助教程(哔哩哔哩)1、每一步都需要思考,不同水...
外挂指南!佛手大菠萝13道挂哪... 外挂指南!佛手大菠萝13道挂哪里,xpoker透视辅助-其实有辅助插件(哔哩哔哩)1、佛手大菠萝13...
外挂操作!agpoker辅助,... 外挂操作!agpoker辅助,哈糖大菠萝挂-竟然一直总是有辅助软件(哔哩哔哩)1、用户打开应用后不用...
外挂积累!拱趴大菠萝万能挂,h... 外挂积累!拱趴大菠萝万能挂,hardrock透视工具-一贯存在有辅助脚本(哔哩哔哩)1、下载好拱趴大...
外挂经验!德普之星透视辅助软件... 外挂经验!德普之星透视辅助软件激活码,悦扑克脚本-其实有辅助神器(哔哩哔哩)1、游戏颠覆性的策略玩法...
外挂诀窍!德普之星透视,拱趴大... 外挂诀窍!德普之星透视,拱趴大菠萝万能辅助器-原来有辅助工具(哔哩哔哩)1、下载好拱趴大菠萝万能辅助...