![](/img/trans.png)
[英]Using WebSockets to communicate between Java and C# desktop applications?
[英]Using the GCM service to communicate between 2 applications
我正在尝试创建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的代码:
以下代码是从主要活动调用的服务:
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的消息。
同样,您不应该以这种方式在应用程序之间直接推送消息,因为这将要求您将私有API密钥发送到应用程序包中才能发送消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.