我正在使用eclipse为Android开发一个应用程序,我基本上想要做的是:
将我的设备(1)的通知发送到另一台设备(2)。
我使用的用户登录已经配置了数据库。
当我按下用户时(当我按下发送通知的按钮时)。
我希望设备1发送在设备2上显示的通知。
两个设备都使用不同的用户登录,但我无法使通知部分正常工作。
编辑:当我按下按钮时,通知显示在设备1上,但我希望它显示在设备2上...
这是接收通知的代码:
public void NmRecv(String username, String message)
{
FriendInfo friend = FriendController.getFriendInfo(username);
MessageInfo msg = MessageController.checkMessage(username);
if ( msg != null)
{
Intent i = new Intent(TAKE_MESSAGE);
i.putExtra(MessageInfo.USERID, msg.userid);
i.putExtra(MessageInfo.MESSAGETEXT, msg.messagetext);
sendBroadcast(i);
String activeFriend = FriendController.getActiveFriend();
if (activeFriend == null || activeFriend.equals(username) == false)
{
localstoragehandler.insert(username,this.getUsername(), message.toString());
showNotification(username, message);
}
}
}
任何想法?
答案 0 :(得分:1)
您可以使用Google Cloud Messaging实现这一目标。
同时检查此link。
您必须注册Android设备的密钥才能发送通知。
换句话说。您需要在登录时将设备的密钥存储在数据库中。
然后当device1想要向设备2发送通知时,您可以使用GCM和存储在数据库中的设备2密钥来执行该操作。
以下是我使用服务器端使用GCM发送消息的代码示例:
Sender sender = new Sender (SENDER_API_CODE);
Message message = new Message.Builder ()
.collapseKey ("1")
.timeToLive (2419200)
.delayWhileIdle (false)
.addData ("message", "example message")
.build ();
result = sender.send (message, reGid, sendCount);
接收方必须使用以下操作创建广播接收器:
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="com.google.android.c2dm.intent.GCM_RECEIVED_ACTION" />
然后当您收到意图时,您会收到如下消息:
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType))
{
//Here you process the intent like you normally would
//String parameter = intent.getStringExtra("name of parameter");
//...
//After that you can create a notification like in the link below.
}
<强> creating notifications 强>