我编写了一个程序,使用jsp在Android中实现Google Cloud Messaging。从这里得到了参考(http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/) 当我尝试在我的eclipse中运行程序时,我无法在服务器上运行它给我GCMRegId.txt缺少错误。 以下是代码:
GCMNotification.java
@WebServlet("/GCMNotification")
public class GCMNotification extends HttpServlet {
private static final String GOOGLE_SERVER_KEY = "AIzaSyDA5dlLInMsasJEUTIHV0u7maB82MCasdU";
static final String MESSAGE_KEY = "message";
public GCMNotification() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Result result = null;
String share = request.getParameter("shareRegId");
// GCM RedgId of Android device to send push notification
String regId = "APA91bG6cLX8OYyZDRypuRq6uodZ9PuMfiql9k6K66i9hZFnS5xr-QmT13nRozGQ10KXNmcMqbsLCVUIS9joGiOPasdfghjklp_AmH2iNs1YVqY3IYzgHoQ";
if (share != null && !share.isEmpty()) {
regId = request.getParameter("regId");
PrintWriter writer = new PrintWriter("GCMRegId.txt");
writer.println(regId);
writer.close();
request.setAttribute("pushStatus", "GCM RegId Received.");
request.getRequestDispatcher("index.jsp")
.forward(request, response);
} else {
try {
BufferedReader br = new BufferedReader(new FileReader(
"GCMRegId.txt"));
regId = br.readLine();
br.close();
String userMessage = request.getParameter("message");
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(30)
.delayWhileIdle(true).addData(MESSAGE_KEY, userMessage).build();
System.out.println("regId: " + regId);
result = sender.send(message, regId, 1);
request.setAttribute("pushStatus", result.toString());
} catch (IOException ioe) {
ioe.printStackTrace();
request.setAttribute("pushStatus",
"RegId required: " + ioe.toString());
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("pushStatus", e.toString());
}
request.getRequestDispatcher("index.jsp")
.forward(request, response);
}
}
JSP页面: index.jsp的
<head>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in Java</h1>
<%
String pushStatus = "";
Object pushStatusObj = request.getAttribute("pushStatus");
if (pushStatusObj != null) {
pushStatus = pushStatusObj.toString();
}
%>
<form action="GCMNotification" method="post">
<div>
<textarea rows="2" name="message" cols="23"
placeholder="Message to transmit via GCM"></textarea>
</div>
<div>
<input type="submit" value="Send Push Notification via GCM" />
</div>
</form>
<p>
<h3>
<%=pushStatus%>
</h3>
</p>
它总是给我错误 RegId要求:java.io.FileNotFoundException:GCMRegId.txt(系统找不到指定的文件) 我怎么能解决这个错误???
答案 0 :(得分:0)
嘿伙计们我解决了这个问题。 GCMRegId.txt文件自动生成。不手动创建该文件。
或者,如果您不想让GCMRegId.txt文件只是从您的代码中删除,并将DeviceId传递给regID(字符串)并删除未使用的代码。
你会得到你的输出。 感谢。