zac*_*ria 8 php java mysql android push-notification
我正在编写一个Android应用程序,我需要向一组用户发送通知.
我在数据库中有两组用户.如果用户在Android应用程序中按下"通知组1"按钮,我需要将通知发送给所有组1用户.我如何实现这个逻辑?我认为在群聊中使用相同的逻辑.
你能为我提供android和服务器端的示例代码吗?
谢谢.. Zacharia
使用Android Cloud to Device Messaging是最好的方法,因为您可以轻松地将其与MySQL和PhP集成,拥有通过Internet发送消息的必要工具.
您可以根据需要对用户进行分组:
CREATE TABLE IF NOT EXISTS `gcm_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`gcm_regid` text,
`name` varchar(50) NOT NULL,
`email` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Run Code Online (Sandbox Code Playgroud)
来源 - AndroidHive
在这里,您有一个典型的示例,其中包含使用Google云通过Internet发送消息的Java类:
public class MessageUtil {
private final static String AUTH = "authentication";
private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
public static int sendMessage(String auth_token, String registrationId,
String message) throws IOException {
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
.append(registrationId);
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
.append("0");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode(message, UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
// Hit the dm URL.
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpsURLConnection
.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ auth_token);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
return responseCode;
}
private static class CustomizedHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了将其包装起来,您可以使用MySQL将您的查询与PhP集成以实现您想要的效果.这里有服务器端的PhP示例:
send_message.php
<?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
Run Code Online (Sandbox Code Playgroud)
在这里,您可以找到一些可能出现的其他示例,包括系统逻辑:
从这里开始,您可以使用您的功能获得您的应用程序.