GCM推送通知不工作,并登记身份证,也没有显示 [英] GCM push notification not working , and register id is also not displaying
问题描述
我已经写了一个程序GCM注册和注册ID共享到一个新的活动,但不幸的是,当我在寄存器按钮点击,当我在发送推送通知按钮点击jsp页面它放在我的注册ID本身不显示我投它说一个错误的 文件未发现异常GCMRegId.txt
。照片如果有人可以建议我,我的变化作出以下code,这将是很大的帮助。
I have written a program for GCM to register and share the registered id to a new activity , but unfortunately my register id is itself not showing when i click on register button and when i click on send push notification button on jsp page it throws me an error which says "File Not Found Exception GCMRegId.txt"
.
If someone can suggest me the changes that i have to make to the following code , it would be of great help
GCMNotification.java
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
有两个按钮,一个用于分享,上注册按钮注册和其他
我已经把敬酒,但是当我点击它,它让我REGID是:没有REGID显示
,当我在分享按钮点击,它显示的 REGID是空的
RegistrationActivity.java
which has two button one for Registering and other for sharing, On register button
i have put a toast but when i click on it , it shows me "RegId is : " , no regid is shown
and when i click on share button , it shows "RegId is empty"
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();
}
GCMNotificationIntentService.java
GCMNotificationIntentService.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.");
}
Config.java
Config.java
public interface Config {
// GCM server using java
static final String APP_SERVER_URL = "http://192.168.1.17:8081/GCM-App-Server/GCMNotification?
shareRegId=1";
// Google Project Number
static final String GOOGLE_PROJECT_ID = "167543534432";
static final String MESSAGE_KEY = "message";
}
当我在通过从index.jsp页面GCM按钮推送通知点击,这是它显示了错误
When i click on the button push notification via GCM from index.jsp page , this is the error it shows
java.io.FileNotFoundException:GCMRegId.txt(系统找不到指定的文件)
在java.io.FileInputStream.open(本机方法)
在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)
在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)
在org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:607)
在org.apache.tomcat.util.net.A prendpoint $ SocketProcessor.doRun(A prendpoint.java:2441)
在org.apache.tomcat.util.net.A prendpoint $ SocketProcessor.run(A prendpoint.java:2430)
在java.util.concurrent.ThreadPoolExecutor.runWorker(来源不明)
在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(来源不明)
在java.lang.Thread.run(来源不明)
java.io.FileNotFoundException: GCMRegId.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(Unknown Source) at java.io.FileInputStream.(Unknown Source) at java.io.FileReader.(Unknown Source) at com.android.d_governance.GCMNotification.doPost(GCMNotification.java:55) at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at 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) at java.lang.Thread.run(Unknown Source)
我的LogCat中:
12月1日至12日:05:07.765:D / RegisterActivity(20445):registerGCM - 与GCM服务器成功注册 - REGID:
12月1日至12日:05:07.765:D / RegisterActivity(20445):GCM REGID:
01-12 12:05:07.765: D/RegisterActivity(20445): registerGCM - successfully registered with GCM server - regId: 01-12 12:05:07.765: D/RegisterActivity(20445): GCM RegId:
没有GCM REGID被显示出来。
No GCM RegId is showing up
请需要显示我的REGID一些帮助
感谢你
Please need some help in displaying my regid Thanking You
推荐答案
使用这种方法,而不是getRegistrationId();
Use this method instead of 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;
}
这篇关于GCM推送通知不工作,并登记身份证,也没有显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!