我已经为GCM编写了一个程序来注册并将注册的id分享给一个新的活动,但不幸的是,当我点击注册按钮时我的注册ID本身没有显示,当我点击jsp页面上的发送推送通知按钮时抛出一个错误,上面写着 "File Not Found Exception GCMRegId.txt"
。
如果有人可以建议我对以下代码所做的更改,那将会有很大的帮助
GCMNotification.java
@WebServlet("/GCMNotification")
public class GCMNotification extends HttpServlet {
private static final long serialVersionUID = 1L;
// Put your Google API Server Key here
private static final String GOOGLE_SERVER_KEY = "Server Key";
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 = "";
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);
}
}
RegistrationActivity.java
,其中有两个按钮用于注册,另一个按钮用于共享,On register button
我已经举杯祝酒,但是当我点击它时,它会显示{{1}当我点击分享按钮时,它会显示 "RegId is : " , no regid is shown
"RegId is empty"
GCMNotificationIntentService.java
public class RegisterGCMActivity extends Activity {
GoogleCloudMessaging gcm;
Context context;
String registerId;
Button btnGCMRegister;
Button btnAppShare;
public static final String REG_ID = "regId";
private static final String APP_VERSION = "appVersion";
String passedData;
TextView txtHeader;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.reg_gcm);
txtHeader = (TextView) findViewById(R.id.txtHeader);
passedData = getIntent().getStringExtra("name");
txtHeader.setText(passedData);
context = getApplicationContext();
btnGCMRegister = (Button) findViewById(R.id.buttonReg);
btnGCMRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (TextUtils.isEmpty(registerId)) {
registerId = registerGCM();
Log.d("RegisterActivity", "GCM RegId: " + registerId);
Toast.makeText(getBaseContext(), "RegId is :" + registerId,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Already Registered with GCM Server!",
Toast.LENGTH_LONG)
.show();
}
}
});
btnAppShare = (Button) findViewById(R.id.buttonShare);
btnAppShare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (TextUtils.isEmpty(registerId)) {
Toast.makeText(getApplicationContext(), "RegId is empty!",
Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(getApplicationContext(), Service_Access.class);
i.putExtra("regId", registerId);
Log.d("RegisterActivity",
"onClick of Share: Before starting main activity.");
startActivity(i);
finish();
Log.d("RegisterActivity", "onClick of Share: After finish.");
}
}
});
}
public String registerGCM() {
gcm = GoogleCloudMessaging.getInstance(this);
registerId = getRegistrationId(context);
if (TextUtils.isEmpty(registerId)) {
registerInBackground();
Log.d("RegisterActivity", "registerGCM - successfully registered with GCM server - regId:
" + registerId);
} else {
Toast.makeText(getApplicationContext(), "RegId already available. RegId: " + registerId,
Toast.LENGTH_LONG)
.show();
}
return registerId;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
String registrationId = prefs.getString(REG_ID, "");
if (registrationId.isEmpty()) {
// Log.i(TAG, "Registration not found.");
return "";
}
int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
// Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo =
context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
Log.d("RegisterActivity", "I never expected this! Going down, going down!" + e);
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private void registerInBackground() {
new AsyncTask() {
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
registerId = gcm.register(com.android.d_governance.Config.GOOGLE_PROJECT_ID);
Log.d("RegisterActivity", "registerInBackground - regId: " + registerId);
msg = "Device registered, registration ID=" + registerId;
storeRegistrationId(context, registerId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
Log.d("RegisterActivity", "Error: " + msg);
}
Log.d("RegisterActivity", "AsyncTask completed: " + msg);
return msg;
}
protected void onPostExecute(String msg) {
Toast.makeText(getApplicationContext(), "Registered with GCM Server." + msg,
Toast.LENGTH_LONG).show();
}
@Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
return null;
}
}.execute(null, null, null);
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getSharedPreferences(Service_Access.class.getSimpleName(),
Context.MODE_PRIVATE);
int appVersion = getAppVersion(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(REG_ID, regId);
editor.putInt(APP_VERSION, appVersion);
editor.commit();
}
Config.java
public class GCMNotificationIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
for (int i = 0; i < 3; i++) {
// Log.i(TAG, "Working... " + (i + 1) + "/5 @ " +
// SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
// Log.i(TAG, "Completed work @ " +
// SystemClock.elapsedRealtime());
sendNotification("Message Received from Google GCM Server: " +
extras.get(Config.MESSAGE_KEY));
// Log.i(TAG, "Received: " + extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
// Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
Service_Access.class), 0);
NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(this).setSmallIcon(R.drawable.gcm_logo)
.setContentTitle("GCM Notification").setStyle(new
NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
// Log.d(TAG, "Notification sent successfully.");
}
当我从index.jsp页面通过GCM点击按钮推送通知时,这是它显示的错误
java.io.FileNotFoundException:GCMRegId.txt(系统找不到指定的文件) at java.io.FileInputStream.open(Native Method) 在java.io.FileInputStream。(未知来源) 在java.io.FileInputStream。(未知来源) 在java.io.FileReader。(未知来源) 在com.android.d_governance.GCMNotification.doPost(GCMNotification.java:55) 在javax.servlet.http.HttpServlet.service(HttpServlet.java:646) 在javax.servlet.http.HttpServlet.service(HttpServlet.java:727) 在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) 在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) 在org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) 在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) 在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) 在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) 在org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) 在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) 在org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) 在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) 在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) 在org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:607) 在org.apache.tomcat.util.net.AprEndpoint $ SocketProcessor.doRun(AprEndpoint.java:2441) at org.apache.tomcat.util.net.AprEndpoint $ SocketProcessor.run(AprEndpoint.java:2430) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor $ Worker.run(Unknown Source) 在java.lang.Thread.run(未知来源)
我的LogCat:
01-12 12:05:07.765:D / RegisterActivity(20445):registerGCM - 已成功注册GCM服务器 - regId: 01-12 12:05:07.765:D / RegisterActivity(20445):GCM RegId:
没有GCM RegId出现
在显示我的注册表时需要一些帮助 感谢你
答案 0 :(得分:0)
使用此方法代替getRegistrationId();
private String getRegistrationId(Context context)
{
final SharedPreferences prefs = getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
String registrationId = prefs.getString(REG_ID, "");
if (registrationId=="")
{
registerInBackground();
}
else
{
Toast.makeText(getApplicationContext(),"RegId already available. RegId: " + registrationId, Toast.LENGTH_SHORT).show();
}
int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion)
{
return "";
}
return registrationId;
}