为什么GCM是不会放弃在Android设备推送通知? [英] why GCM is not giving push notification in android device?
问题描述
我是新来的Android和做的GCM推送通知的演示应用程序。
我已经开发了这一切code和GCM推送通知是在设备未来在我的环境,但是当我测试的其他网络设备这个code获得注册ID,但服务器端获取不匹配发件人ID响应时将消息发送到云。
我的code为波纹管式给出:
checkNotNull(CommonUtilities.SENDER_IDSENDER_ID); GCMRegistrar.checkDevice(本);
GCMRegistrar.checkManifest(本); 的setContentView(R.layout.activity_push_android);
填充mDisplay =(的TextView)findViewById(R.id.display); 最后弦乐REGID = GCMRegistrar.getRegistrationId(本);
Log.i(TAG,注册ID =====+ REGID); 如果(regId.equals()){
GCMRegistrar.register(这一点,CommonUtilities.SENDER_ID);
}其他{
//设备已登记在GCM
如果(GCMRegistrar.isRegisteredOnServer(本)){
//跳过注册。
Toast.makeText(getApplicationContext(),
已经与GCM注册,Toast.LENGTH_LONG)
。显示();
}其他{
//尝试再次注册,但不是在UI线程。
//这也是必要取消线程的onDestroy()
//因此,使用AsyncTask的,而不是一个原始的线程。
//最后上下文的背景下=这;
mRegisterTask =新的AsyncTask<太虚,太虚,太虚>(){ @覆盖
保护无效doInBackground(虚空...... PARAMS){
//注册我们的服务器上
//在服务器上创建一个新用户
// ServerUtilities.register(上下文,姓名,电子邮件,
// REGID);
返回null;
} @覆盖
保护无效onPostExecute(虚空结果){
mRegisterTask = NULL;
mDisplay.setText(FFFFFF+ REGID);
} };
mRegisterTask.execute(NULL,NULL,NULL);
}
}
// REGID = GCMRegistrar.getRegistrationId(本);
mDisplay.setText(FFFFFF+ REGID);
Log.i(TAG,注册ID ===== !!!!+ REGID);
}私人无效checkNotNull(对象引用,字符串名称){
如果(参考== NULL){
抛出新的NullPointerException(的getString(R.string.error_config,
名称));
}
}@覆盖
保护无效的onPause(){
super.onPause();
GCMRegistrar.unregister(本);
}
}
接收器:
公共GCMIntentService(){
超(CommonUtilities.SENDER_ID);}私有静态最后弦乐TAG ==== GCMIntentService ===@覆盖
保护无效onRegistered(上下文为arg0,弦乐registrationId){
Log.i(TAG,设备注册:REGID =+ registrationId);
}@覆盖
保护无效onUnregistered(上下文为arg0,ARG1字符串){
Log.i(TAG未注册=+ ARG1);
}@覆盖
保护无效的onMessage(上下文为arg0,意向留言){
捆绑额外= message.getExtras(); 对于(字符串键:extras.keySet()){
Log.d(的getClass()。getSimpleName(),
的String.format(的onMessage:%s =%S键,
extras.getString(键))); Toast.makeText(getApplicationContext(),HII,Toast.LENGTH_LONG)
。显示();
}
Log.i(TAG,新的消息=); // /////////////////// 时长= System.currentTimeMillis的();
NotificationManager notificationManager =(NotificationManager)上下文
.getSystemService(Context.NOTIFICATION_SERVICE);
通知通知=新的通知(R.drawable.ic_launcher,
(CharSequence的)消息,时);
字符串title = context.getString(R.string.app_name);
意图notificationIntent =新意图(背景下,
PushAndroidActivity.class);
//设置的意图,因此它不会启动新活动
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
的PendingIntent意图= PendingIntent.getActivity(上下文,0,
notificationIntent,0);
notification.setLatestEventInfo(上下文,标题,(CharSequence的)消息,
意图);
notification.flags | = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0,通知);
}@覆盖
保护无效的onError(上下文为arg0,弦乐ErrorID中){
Log.i(TAG,收到的错误:+ ErrorID中);
}@覆盖
保护布尔onRecoverableError(上下文的背景下,字符串ErrorID中){
返回super.onRecoverableError(背景下,ErrorID中);
}
}
这code给了我一个注册ID successfully.To测试我的code我已经执行一个Java类的发送信息至cloud.That java类是:
公共静态无效的主要(字符串ARGS []){ 尝试{ 发件人发送者=新的发件人(
我的服务器API); ArrayList的<串GT; devicesList =新的ArrayList<串GT;(); devicesList
。新增(章ID);
// devicesList.add(章ID); //使用此线来发送消息,而有效载荷数据
//消息消息=新Message.Builder()建立()。 //使用此行与有效载荷数据发送消息
消息消息=新Message.Builder()
.collapseKey(1)
.timeToLive(3)
.delayWhileIdle(真)
.addData(信息,
这一文本将在通知栏上看到!)
。建立(); //使用这个code发送到单个设备
//结果结果=发件人
// 。发信息,
// \"APA91bGiRaramjyohc2lKjAgFGpzBwtEmI8tJC30O89C2b3IjP1CuMeU1h9LMjKhmWuZwcXZjy1eqC4cE0tWBNt61Kx_SuMF6awzIt8WNq_4AfwflaVPHQ0wYHG_UX3snjp_U-5kJkmysdRlN6T8xChB1n3DtIq98w\",
// 1); //使用这个对多播消息
MulticastResult结果= sender.send(消息,devicesList,1);
sender.send(消息,devicesList,1); 的System.out.println(result.toString()+\\ n);
如果(result.getResults()!= NULL){
INT canonicalRegId = result.getCanonicalIds();
如果(canonicalRegId!= 0){
的System.out.println(canonicalRegId);
}
}其他{
INT错误= result.getFailure();
的System.out.println(错误);
}
}赶上(例外五){
e.printStackTrace();
}
}
}
现在的问题是,我没有得到任何推送通知或登录猫message.Thanks提前寻求帮助。
清单:
SDK
安卓的minSdkVersion =8
机器人:targetSdkVersion =16/>
<许可
机器人:名字=com.sagar.gcma.permission.C2D_MESSAGE
安卓的ProtectionLevel =签名/><使用许可权的android:NAME =com.sagar.gcma.permission.C2D_MESSAGE/>
<使用许可权的android:NAME =android.permission.GET_ACCOUNTS/>
<使用许可权的android:NAME =android.permission.WAKE_LOCK/>
<使用许可权的android:NAME =android.permission.INTERNET对/>
<使用许可权的android:NAME =com.google.android.c2dm.permission.RECEIVE/><应用
机器人:图标=@绘制/ ic_launcher
机器人:标签=@字符串/ APP_NAME
机器人:主题=@风格/ AppTheme>
<活动
机器人:名字=。PushAndroidActivity
机器人:标签=@字符串/ title_activity_push_android>
&所述;意图滤光器>
<作用机器人:名字=android.intent.action.MAIN/> <类机器人:名字=android.intent.category.LAUNCHER/>
&所述; /意图滤光器>
< /活性GT; <接收
机器人:名字=com.google.android.gcm.GCMBroadcastReceiver
机器人:权限=com.google.android.c2dm.permission.SEND>
&所述;意图滤光器>
<作用机器人:名字=com.google.android.c2dm.intent.RECEIVE/>
<作用机器人:名字=com.google.android.c2dm.intent.REGISTRATION/> <类机器人:名字=com.sagar.gcma/>
&所述; /意图滤光器>
< /接收器> <服务机器人。GCMIntentServiceNAME = />
< /用途>
最后我找到了reason.My公司防火墙挡住从GCM的所有消息。所以我只是删除防火墙和能够接收来自GCM 消息。通过这个链接去了解更多关于防火墙问题
希望这将帮助别人在未来。
I am new to android and doing a demo app for gcm push notification.
I have developed all this code and GCM push notification is coming on devices in my environment, but when I test this code in other network device gets registration id,but server side gets mismatch sender id response when sending messages to cloud. My code is given bellow:
checkNotNull(CommonUtilities.SENDER_ID, "SENDER_ID");
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
setContentView(R.layout.activity_push_android);
mDisplay = (TextView) findViewById(R.id.display);
final String regId = GCMRegistrar.getRegistrationId(this);
Log.i(TAG, "registration id ===== " + regId);
if (regId.equals("")) {
GCMRegistrar.register(this, CommonUtilities.SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(),
"Already registered with GCM", Toast.LENGTH_LONG)
.show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
// final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
// ServerUtilities.register(context, name, email,
// regId);
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
mDisplay.setText("ffffff " + regId);
}
};
mRegisterTask.execute(null, null, null);
}
}
// regId = GCMRegistrar.getRegistrationId(this);
mDisplay.setText("ffffff " + regId);
Log.i(TAG, "registration id =====!!!! " + regId);
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(getString(R.string.error_config,
name));
}
}
@Override
protected void onPause() {
super.onPause();
GCMRegistrar.unregister(this);
}
}
receiver:
public GCMIntentService() {
super(CommonUtilities.SENDER_ID);
}
private static final String TAG = "===GCMIntentService===";
@Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
}
@Override
protected void onUnregistered(Context arg0, String arg1) {
Log.i(TAG, "unregistered = " + arg1);
}
@Override
protected void onMessage(Context arg0, Intent message) {
Bundle extras = message.getExtras();
for (String key : extras.keySet()) {
Log.d(getClass().getSimpleName(),
String.format("onMessage: %s=%s", key,
extras.getString(key)));
Toast.makeText(getApplicationContext(), "hii", Toast.LENGTH_LONG)
.show();
}
Log.i(TAG, "new message= ");
// ///////////////////
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
(CharSequence) message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context,
PushAndroidActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, (CharSequence) message,
intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
@Override
protected void onError(Context arg0, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}
}
This code has given me a registration id successfully.To test my code I have executed a java class to send message to cloud.That java class is:
public static void main(String args[]) {
try {
Sender sender = new Sender(
"my server api");
ArrayList<String> devicesList = new ArrayList<String>();
devicesList
.add("reg id");
// devicesList.add("reg id");
// Use this line to send message without payload data
// Message message = new Message.Builder().build();
// use this line to send message with payload data
Message message = new Message.Builder()
.collapseKey("1")
.timeToLive(3)
.delayWhileIdle(true)
.addData("message",
"this text be will be seen in notification bar!!")
.build();
// Use this code to send to a single device
// Result result = sender
// .send(message,
// "APA91bGiRaramjyohc2lKjAgFGpzBwtEmI8tJC30O89C2b3IjP1CuMeU1h9LMjKhmWuZwcXZjy1eqC4cE0tWBNt61Kx_SuMF6awzIt8WNq_4AfwflaVPHQ0wYHG_UX3snjp_U-5kJkmysdRlN6T8xChB1n3DtIq98w",
// 1);
// Use this for multicast messages
MulticastResult result = sender.send(message, devicesList, 1);
sender.send(message, devicesList, 1);
System.out.println(result.toString() + "\n");
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
System.out.println(canonicalRegId);
}
} else {
int error = result.getFailure();
System.out.println(error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now the problem is I am not getting any push notification or log cat message.Thanks in advance for help. Manifest:
sdk android:minSdkVersion="8" android:targetSdkVersion="16" />
<permission
android:name="com.sagar.gcma.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.sagar.gcma.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".PushAndroidActivity"
android:label="@string/title_activity_push_android" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.sagar.gcma" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
At last I found the reason.My company firewall was blocking all messages from GCM. So I just removed firewall and able to receive messages from GCM . Go through this link to know more about firewall issues
Hope it will help somebody in future.
这篇关于为什么GCM是不会放弃在Android设备推送通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!