未使用GCM接收推送通知(Not receiving push notification using GCM)
我正在使用GCM实现推送通知。我成功获得令牌和实例ID,服务器也在发送通知时返回成功,但我无法在手机上显示通知。 请帮忙!!!
以下是我的代码
Android清单:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- [START gcm_permission] --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- [END gcm_permission] --> <permission android:name="com.example.appname.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="com.example.appname.permission.C2D_MESSAGE" /> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" /> <application android:allowBackup="true" android:icon="@drawable/appicon" android:label="@string/app_name" android:theme="@style/Theme.AppCompat.NoActionBar"> <activity android:name=".Outlet.Activities.SplashActivity" android:label="@string/app_name" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="gcm_test_app_notification_click_action"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <activity android:name=".Outlet.Activities.LoginActivity" android:screenOrientation="portrait" /> <service android:name="com.paypal.android.sdk.payments.PayPalService" android:exported="false" /> <activity android:name="com.paypal.android.sdk.payments.PaymentActivity" /> <activity android:name="com.paypal.android.sdk.payments.LoginActivity" /> <activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity" /> <activity android:name="com.paypal.android.sdk.payments.PaymentConfirmActivity" /> <activity android:name="io.card.payment.CardIOActivity" android:configChanges="keyboardHidden|orientation" /> <activity android:name="io.card.payment.DataEntryActivity" /> <!-- [START gcm_receiver] --> <receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" 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.example.appname" /> <!--<category android:name="gcm.play.android.samples.com.gcmquickstart" />--> </intent-filter> </receiver> <!-- [END gcm_receiver] --> <!-- [START gcm_listener] --> <service android:name="com.example.appname.CommonFiles.Push.MyGcmListenerService" android:exported="false" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> </intent-filter> </service> <!-- [END gcm_listener] --> <!-- [START instanceId_listener] --> <service android:name="com.example.appname.CommonFiles.Push.MyInstanceIDListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.android.gms.iid.InstanceID"/> </intent-filter> </service> <!-- [END instanceId_listener] --> <service android:name="com.example.appname.CommonFiles.Push.RegistrationIntentService" android:exported="false"> </service> </application> </manifest>
GCMIntentservice类: -
public class MyGcmListenerService extends GcmListenerService { private static final String TAG = "MyGcmListenerService"; public static final int MESSAGE_NOTIFICATION_ID = 435345; /** * Called when message is received. * * @param from SenderID of the sender. * @param data Data bundle containing message data as key/value pairs. * For Set of keys use data.keySet(). */ // [START receive_message] @Override public void onMessageReceived(String from, Bundle data) { String message = data.getString("message"); Log.d(TAG, "From: " + from); Log.d(TAG, "Message: " + message); if (from.startsWith("/topics/")) { // message received from some topic. } else { // normal downstream message. } // [START_EXCLUDE] /** * Production applications would usually process the message here. * Eg: - Syncing with server. * - Store message in local database. * - Update UI. */ /** * In some cases it may be useful to show a notification indicating to the user * that a message was received. */ sendNotification(message); // [END_EXCLUDE] } // [END receive_message] /** * Create and show a simple notification containing the received GCM message. * * @param message GCM message received. */ private void sendNotification(String message) { Intent intent = new Intent(this, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("GCM Message") .setContentText(message) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(MESSAGE_NOTIFICATION_ID /* ID of notification */, notificationBuilder.build()); } }
RegisterIntentService: -
public class RegistrationIntentService extends IntentService { private static final String TAG = "RegIntentService"; private static final String[] TOPICS = {"global"}; UserSession userSession; public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); userSession=new UserSession(this); try { // [START register_for_gcm] // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. // [START get_token] InstanceID instanceID = InstanceID.getInstance(this); // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json. // See https://developers.google.com/cloud-messaging/android/start for details on this file. String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); userSession.saveGCMToken(token); // [END get_token] Log.i(TAG, "GCM Registration Token: " + token); // TODO: Implement this method to send any registration to your app's servers. sendRegistrationToServer(token); // Subscribe to topic channels subscribeTopics(token); // You should store a boolean that indicates whether the generated token has been // sent to your server. If the boolean is false, send the token to your server, // otherwise your server should have already received the token. sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply(); // [END register_for_gcm] } catch (Exception e) { Log.d(TAG, "Failed to complete token refresh", e); // If an exception happens while fetching the new token or updating our registration data // on a third-party server, this ensures that we'll attempt the update at a later time. sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply(); } // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } /** * Persist registration to third-party servers. * * Modify this method to associate the user's GCM registration token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { // Add custom implementation, as needed. GCMHelper gcmHelper = new GCMHelper(this); gcmHelper.checkRegisterDevice(); } /** * Subscribe to any GCM topics of interest, as defined by the TOPICS constant. * * @param token GCM token * @throws IOException if unable to reach the GCM PubSub service */ // [START subscribe_topics] private void subscribeTopics(String token) throws IOException { GcmPubSub pubSub = GcmPubSub.getInstance(this); for (String topic : TOPICS) { pubSub.subscribe(token, "/topics/" + topic, null); } } // [END subscribe_topics] }
I am implementing push notification using GCM.I m getting the token and instance id successfully, the server is also returning success on sending the notification but i m unable to reveive notification on my phone. Please help!!!
Below is my code
Android Manifest:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- [START gcm_permission] --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- [END gcm_permission] --> <permission android:name="com.example.appname.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="com.example.appname.permission.C2D_MESSAGE" /> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" /> <application android:allowBackup="true" android:icon="@drawable/appicon" android:label="@string/app_name" android:theme="@style/Theme.AppCompat.NoActionBar"> <activity android:name=".Outlet.Activities.SplashActivity" android:label="@string/app_name" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="gcm_test_app_notification_click_action"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <activity android:name=".Outlet.Activities.LoginActivity" android:screenOrientation="portrait" /> <service android:name="com.paypal.android.sdk.payments.PayPalService" android:exported="false" /> <activity android:name="com.paypal.android.sdk.payments.PaymentActivity" /> <activity android:name="com.paypal.android.sdk.payments.LoginActivity" /> <activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity" /> <activity android:name="com.paypal.android.sdk.payments.PaymentConfirmActivity" /> <activity android:name="io.card.payment.CardIOActivity" android:configChanges="keyboardHidden|orientation" /> <activity android:name="io.card.payment.DataEntryActivity" /> <!-- [START gcm_receiver] --> <receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" 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.example.appname" /> <!--<category android:name="gcm.play.android.samples.com.gcmquickstart" />--> </intent-filter> </receiver> <!-- [END gcm_receiver] --> <!-- [START gcm_listener] --> <service android:name="com.example.appname.CommonFiles.Push.MyGcmListenerService" android:exported="false" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> </intent-filter> </service> <!-- [END gcm_listener] --> <!-- [START instanceId_listener] --> <service android:name="com.example.appname.CommonFiles.Push.MyInstanceIDListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.android.gms.iid.InstanceID"/> </intent-filter> </service> <!-- [END instanceId_listener] --> <service android:name="com.example.appname.CommonFiles.Push.RegistrationIntentService" android:exported="false"> </service> </application> </manifest>
GCMIntentservice class:-
public class MyGcmListenerService extends GcmListenerService { private static final String TAG = "MyGcmListenerService"; public static final int MESSAGE_NOTIFICATION_ID = 435345; /** * Called when message is received. * * @param from SenderID of the sender. * @param data Data bundle containing message data as key/value pairs. * For Set of keys use data.keySet(). */ // [START receive_message] @Override public void onMessageReceived(String from, Bundle data) { String message = data.getString("message"); Log.d(TAG, "From: " + from); Log.d(TAG, "Message: " + message); if (from.startsWith("/topics/")) { // message received from some topic. } else { // normal downstream message. } // [START_EXCLUDE] /** * Production applications would usually process the message here. * Eg: - Syncing with server. * - Store message in local database. * - Update UI. */ /** * In some cases it may be useful to show a notification indicating to the user * that a message was received. */ sendNotification(message); // [END_EXCLUDE] } // [END receive_message] /** * Create and show a simple notification containing the received GCM message. * * @param message GCM message received. */ private void sendNotification(String message) { Intent intent = new Intent(this, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("GCM Message") .setContentText(message) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(MESSAGE_NOTIFICATION_ID /* ID of notification */, notificationBuilder.build()); } }
RegisterIntentService:-
public class RegistrationIntentService extends IntentService { private static final String TAG = "RegIntentService"; private static final String[] TOPICS = {"global"}; UserSession userSession; public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); userSession=new UserSession(this); try { // [START register_for_gcm] // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. // [START get_token] InstanceID instanceID = InstanceID.getInstance(this); // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json. // See https://developers.google.com/cloud-messaging/android/start for details on this file. String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); userSession.saveGCMToken(token); // [END get_token] Log.i(TAG, "GCM Registration Token: " + token); // TODO: Implement this method to send any registration to your app's servers. sendRegistrationToServer(token); // Subscribe to topic channels subscribeTopics(token); // You should store a boolean that indicates whether the generated token has been // sent to your server. If the boolean is false, send the token to your server, // otherwise your server should have already received the token. sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply(); // [END register_for_gcm] } catch (Exception e) { Log.d(TAG, "Failed to complete token refresh", e); // If an exception happens while fetching the new token or updating our registration data // on a third-party server, this ensures that we'll attempt the update at a later time. sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply(); } // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } /** * Persist registration to third-party servers. * * Modify this method to associate the user's GCM registration token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { // Add custom implementation, as needed. GCMHelper gcmHelper = new GCMHelper(this); gcmHelper.checkRegisterDevice(); } /** * Subscribe to any GCM topics of interest, as defined by the TOPICS constant. * * @param token GCM token * @throws IOException if unable to reach the GCM PubSub service */ // [START subscribe_topics] private void subscribeTopics(String token) throws IOException { GcmPubSub pubSub = GcmPubSub.getInstance(this); for (String topic : TOPICS) { pubSub.subscribe(token, "/topics/" + topic, null); } } // [END subscribe_topics] }
原文:https://stackoverflow.com/questions/33516072
更新时间:2023-04-22 09:04
最满意答案
我跑了:
use strict; use warnings; my @Array1=qw/A B C D E/; my @Array2=qw/L B C F E/; foreach my $var (@Array1){ $\=$/; print "Letter $var"; foreach my $var2 (@Array2){ if($var2 eq $var) { print "They are equal"; } else { next; } } }
而且我知道了
Letter A Letter B They are equal Letter C They are equal Letter D Letter E They are equal
I've run it:
use strict; use warnings; my @Array1=qw/A B C D E/; my @Array2=qw/L B C F E/; foreach my $var (@Array1){ $\=$/; print "Letter $var"; foreach my $var2 (@Array2){ if($var2 eq $var) { print "They are equal"; } else { next; } } }
and I've got it
Letter A Letter B They are equal Letter C They are equal Letter D Letter E They are equal
相关问答
更多-
它就像shell中的反引号一样,这就是为什么它被称为。 有关详细信息,请参阅sh (1)。 它单独捕获标准输出,而不是其他任何东西。 它设定了$? 变量为16位等待状态字。 这在perlop (1)手册页中都有解释: qx/STRING/ `STRING` 一个字符串(可能)内插,然后作为系统命令执行,带/bin/sh或其等价物。 壳牌通配符,管道和重定向将受到尊重。 返回收集的命令标准输出; 标准错误不受影响。 在标量上下文中,它作为单个(可能是多行)字符串返回,如果命令失败则返回undef。 在列表上下 ...
-
为什么不改变分割中的正则表达式? split /\s+\D?/, $dash; 如果你想这样将它们添加到@flowers: push( @flowers, split(/\s+\D?/, $dash) ); Why not just change the regex in the split? split /\s+\D?/, $dash; Adding them to @flowers this way if you want: push( @flowers, split(/\s+\D?/, $das ...
-
Perl中匹配的字符数(Character number of match in Perl)[2022-08-28]
请参阅perldoc -f索引 see perldoc -f index -
我跑了: use strict; use warnings; my @Array1=qw/A B C D E/; my @Array2=qw/L B C F E/; foreach my $var (@Array1){ $\=$/; print "Letter $var"; foreach my $var2 (@Array2){ if($var2 eq $var) { print "They are equal"; ...
-
我最好的猜测是你实际上有$word而不是$words ; 一个错字。 如果编译在文本中找到符号$word ,那么它可能就在那里。 但是,我也想对代码发表评论。 清理版本 while (my $words = <$in>) { chomp $words; my $last_duo_idx = length($words) - 2; for my $i (0 .. $last_duo_idx) { my $duo = substr($words, $i, 2); ...
-
这可以是脚本/正则表达式的骨架: use strict; use warnings; use Data::Dumper qw(Dumper); my $str = "The story of Dr. W. Fletcher who is a dentist. The hero of the community."; my @sentences = split /(?您可以使用以下命令轻松过滤掉空条目: @output = grep { /.+/ } @output ; 编辑:您可以更轻松地获得相同的东西: $input = "DEADBEEF"; my @output = ( $input =~ m/.{2}/g ); 编辑2另一个版本: $input = "DEADBEEF"; my @output = unpack("(A2)*", $input); 问候 you can easily filter out the empty entries with: @ ...您需要为每个元素提取第一个数字,并使用<=>运算符进行数值比较, my @array = qw(1-5 7-9 10-15 20-58 123-192 234-256); my @sorted = sort { my ($aa,$bb) = map /^([0-9]+)/, $a,$b; $aa <=> $bb; } @array; You need to extract first number for every element, and do numerical comparison u ...你提到的^A字符是“标题的开头”字符。 您可以将特殊的Perl变量$/设置为此字符。 虽然,如果你希望你的代码可以被追随你的人(并使用另一个编辑器)读取和编辑,我会做这样的事情: use English; local $INPUT_RECORD_SEPARATOR = "\cA" # 'start of heading' character while (<>) { chomp; # remove the unwanted 'start of heading' character pri .../x不修改字符类(或\x20 ,或s{3,4}等)的语法,所以 [^ # characters which are NOT: \w # "word" characters ] # end of character classes 是一种奇怪的写作方式 [^ "#:NOTacdefhilnorst\n\w] /x doesn't modify the syntax of character classes (or of \x2 ...
相关文章
更多- nslocal notification
- HTML5 Notification 桌面提醒功能 API
- Struts2 Push Tag 引发的问题
- Mercurial 如何让中央库在每次被push新内容后都自动update?
- 微信收费事件背后被广泛忽略的技术细节
- 微信收费事件背后被广泛忽略的技术细节
- 微信支付开发(7) 告警通知
- 操作标签-git入门教程
- nginx禁止未绑定域名访问
- 微信支付开发(4) 交易通知
最新问答
更多- 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
- 如何通过引用返回对象?(How is returning an object by reference possible?)
- 矩阵如何存储在内存中?(How are matrices stored in memory?)
- 每个请求的Java新会话?(Java New Session For Each Request?)
- css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
- 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
- xcode语法颜色编码解释?(xcode syntax color coding explained?)
- 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
- 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
- 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
- 西安哪有PLC可控制编程的培训
- 在Entity Framework中选择基类(Select base class in Entity Framework)
- 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
- 电脑二级VF有什么用
- Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
- 金华英语角.
- 手机软件如何制作
- 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
- 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
- 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
- Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
- 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
- python的访问器方法有哪些
- DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
- 在Ruby中对组合进行排序(Sorting a combination in Ruby)
- 网站开发的流程?
- 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
- 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
- 透明度错误IE11(Transparency bug IE11)
- linux的基本操作命令。。。