gpt4 book ai didi

java - 使用 GCM 服务在 2 个应用程序之间进行通信

转载 作者:行者123 更新时间:2023-12-01 14:49:57 25 4
gpt4 key购买 nike

我正在尝试创建 2 个通过 GCM 服务进行通信的应用程序。假设我尝试将字符串从应用程序 A 发送到 B,然后从 B 发送到 A。

我对 GCM 服务非常陌生,我有点困惑。每次看到 myApiCode 时,我都会将其替换为 api 代码。这是 A 代码:

public class MainActivity extends Activity 
{
private final String myApiKey = "903137756997";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "myApiCode");
} else {
Log.v("INFORMATION", "Already registered");
}


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

这是 GCMIntentService:

public class GCMIntentService extends GCMBaseIntentService
{
private final String myApiKey = "903137756997";

public GCMIntentService()
{
super("123");
}
...
@Override
protected void onMessage(Context arg0, Intent arg1)
{
Log.d("GCM", "RECIEVED A MESSAGE");
System.out.println("123123123123");
}
...

}

我附加的代码将是应用程序 A,现在我将附加应用程序 B 的代码:

以下代码是从主 Activity 调用的服务:

public void onCreate()
{
super.onCreate();

Sender sender = new Sender(myApiKey);
Message message = new Message.Builder().build();
Result result = null;
try {
result = sender.send(message, "123", 5);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

if (result.getMessageId() != null) {
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration ID: update database
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister database
}
}
}

我不得不提的是,这两个应用程序都在运行,没有异常,但看起来什么也没发生。我想我在按键上做错了什么,因为我仍然不明白应用程序 B 如何找到应用程序 A。

最佳答案

您必须重写 GCMIntentService 中的 onRegistered 方法。当 GCM 服务器返回由您调用 GCMRegistrar.register 提示的注册 ID 时,将调用此函数。

此方法的实现应将 String 参数上传到您控制的服务器,然后服务器可以发送针对您上传的 ID 的消息。

此外,您不应该以这种方式在应用程序之间直接推送消息,因为它需要您在应用程序包中发送您的私有(private) API key 才能发送消息。

关于java - 使用 GCM 服务在 2 个应用程序之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com