![](/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.