问题:
>当应用程序处于后台或终止状态时,我一次收到2个通知.
>当应用程序处于前台时,只能获得我想要的1个通知.
App should get only 1 notification as requirement but unfortunately facing undefined situation.
我的代码如下:
用于接收消息的GCmpushReceiverService类.
public class GCmpushReceiverService extends GcmListenerService {//This method will be called on every new message received@OverrIDepublic voID onMessageReceived(String from,Bundle data) { //Getting the message from the bundle String message = data.getString("message"); //displaying a notiffication with the message Log.e("MeSs",""+message); sendNotification(this,message,"traccar App"); sendNotification(message);}//This method is generating a notification and displaying the notification //When in frontprivate voID sendNotification(Context context,String notificationText,String notificationTitle) { PowerManager pm = (PowerManager) context .getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = pm.newWakeLock( PowerManager.PARTIAL_WAKE_LOCK,""); wakeLock.acquire(); Intent intent = new Intent(this,Home.class); intent.putExtra("ChatFragment","newChatFound"); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_top); int requestCode = 0; PendingIntent pendingIntent = PendingIntent.getActivity(this,requestCode,intent,PendingIntent.FLAG_ONE_SHOT); Uri sound = ringtoneManager.getDefaultUri(ringtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( context) .setSmallicon(R.drawable.BUG_log_two) .setcolor(color.RED) .setContentTitle(notificationTitle) .setContentText(notificationText) .setDefaults(Notification.DEFAulT_ALL) .setautoCancel(true) .setContentIntent(pendingIntent); notificationmanager notificationmanager = (notificationmanager)getSystemService(Context.NOTIFICATION_SERVICE); notificationmanager.notify(0,notificationBuilder.build()); //0 = ID of notification wakeLock.release();}private voID sendNotification(String message) { Intent intent = new Intent(this,Home.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_top); int requestCode = 0; PendingIntent pendingIntent = PendingIntent.getActivity(this,PendingIntent.FLAG_ONE_SHOT); Uri sound = ringtoneManager.getDefaultUri(ringtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this) .setSmallicon(R.mipmap.ic_launcher) .setContentText(message) .setautoCancel(true) .setContentIntent(pendingIntent); notificationmanager notificationmanager = (notificationmanager)getSystemService(Context.NOTIFICATION_SERVICE); notificationmanager.notify(0,noBuilder.build()); //0 = ID of notification}}
清单文件代码:
<!-- GCM --> <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" /> <category androID:name="com.vk.trackeruser" /> </intent-filter> </receiver> <!-- GCM Receiver Service --> <service androID:name=".Notification.GCmpushReceiverService" androID:exported="false"> <intent-filter> <action androID:name="com.Google.androID.c2dm.intent.RECEIVE" /> </intent-filter> </service> <!-- GCM Registration Intent Service --> <service androID:name=".Notification.GCMRegistrationIntentService" androID:exported="false"> <intent-filter> <action androID:name="com.Google.androID.gms.iID.InstanceID" /> </intent-filter> </service>
GCMRegistrationIntentService类:
public class GCMRegistrationIntentService extends IntentService {//Constants for success and errorspublic static final String REGISTRATION_SUCCESS = "RegistrationSuccess";public static final String REGISTRATION_ERROR = "RegistrationError";public static final String SenderID = "my ID with numeric number ex 9897979";//Class constructorpublic GCMRegistrationIntentService() { super("");}@OverrIDeprotected voID onHandleIntent(Intent intent) { //Registering gcm to the device registerGCM();}private voID registerGCM() { //Registration complete intent initially null Intent registrationComplete = null; //Register token is also null //we will get the token on successfull registration String token = null; try { //Creating an instanceID InstanceID instanceID = InstanceID.getInstance(getApplicationContext()); //Getting the token from the instance ID token = instanceID.getToken(SenderID,GoogleCloudMessaging.INSTANCE_ID_ScopE,null); //displaying the token in the log so that we can copy it to send push notification //You can also extend the app by storing the token in to your server Log.w("GCMRegIntentService","token:" + token); String tokan = token; //on registration complete creating intent with success registrationComplete = new Intent(REGISTRATION_SUCCESS); //Putting the token to the intent registrationComplete.putExtra("token",token); } catch (Exception e) { //If any error occurred Log.w("GCMRegIntentService","Registration error"); registrationComplete = new Intent(REGISTRATION_ERROR); } //Sending the broadcast that registration is completed LocalbroadcastManager.getInstance(this).sendbroadcast(registrationComplete);} }
GCMTokenRefreshListenerService类:
public class GCMTokenRefreshListenerService extends InstanceIDListenerService{ //If the token is changed registering the device again @OverrIDe public voID onTokenRefresh() { Intent intent = new Intent(this,GCMRegistrationIntentService.class); startService(intent); }}
获取我的GCM令牌的类:
in oncreate { //Initializing our broadcast receiver mRegistrationbroadcastReceiver = new broadcastReceiver() { //When the broadcast received //We are sending the broadcast from GCMRegistrationIntentService @OverrIDe public voID onReceive(Context context,Intent intent) { //If the broadcast has received with success //that means device is registered successfully if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_SUCCESS)){ //Getting the registration token from the intent String token = intent.getStringExtra("token"); StaticContents.Gcm_token=token; Log.e("Token",""+token); //displaying the token as toast Toast.makeText(getApplicationContext(),"Registration token:" + token,Toast.LENGTH_LONG).show(); //if the intent is not with success then displaying error messages } else if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_ERROR)){ // Toast.makeText(getApplicationContext(),"GCM registration error!",Toast.LENGTH_LONG).show(); } else { // Toast.makeText(getApplicationContext(),"Error occurred",Toast.LENGTH_LONG).show(); } } }; //Checking play service is available or not int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); //if play service is not available if(ConnectionResult.SUCCESS != resultCode) { //If play service is supported but not installed if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { //displaying message that play service is not installed // Toast.makeText(getApplicationContext(),"Google Play Service is not install/enabled in this device!",Toast.LENGTH_LONG).show(); GooglePlayServicesUtil.showErrorNotification(resultCode,getApplicationContext()); //If play service is not supported //displaying an error message } else { // Toast.makeText(getApplicationContext(),"This device does not support for Google Play Service!",Toast.LENGTH_LONG).show(); } //If play service is available } else { //Starting intent to register device Intent itent = new Intent(this,GCMRegistrationIntentService.class); startService(itent); }} //Registering receiver on activity resume@OverrIDeprotected voID onResume() { super.onResume(); Log.w("MainActivity","onResume"); LocalbroadcastManager.getInstance(this).registerReceiver(mRegistrationbroadcastReceiver,new IntentFilter(GCMRegistrationIntentService.REGISTRATION_SUCCESS)); LocalbroadcastManager.getInstance(this).registerReceiver(mRegistrationbroadcastReceiver,new IntentFilter(GCMRegistrationIntentService.REGISTRATION_ERROR));} //Unregistering receiver on activity paused@OverrIDeprotected voID onPause() { super.onPause();LocalbroadcastManager.getInstance(this).unregisterReceiver(mRegistrationbroadcastReceiver);}
Output 1: When the app in visible (foreground) only one notification is received.
解决方法 1.一旦从GCM收到消息,就会调用GCmpushReceiverService类中的onMessageReceived函数.Output 2: When app is closed or app is in background Getting 2 notifications.
用这个
String message = data.getString("message");
您正在解析并将消息存储在名为message的变量中.
问题是您将消息传递给两个函数
sendNotification(this,"traccar App");sendNotification(message);
这两个函数正在构建一个通知,并将您传递给这两个函数的消息显示为2个单独的通知.
只需注释掉这两个函数中的任何一个并进行检查.
2.为了避免重复通知,有一种方法可以处理它.
尝试改变这个 –
PendingIntent pendingIntent = PendingIntent.getActivity(this,PendingIntent.FLAG_ONE_SHOT);
至
PendingIntent pendingIntent = PendingIntent.getActivity(this,PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
如果问题仍然存在,请发布您获得的有效负载.我建议使用FCM而不是GCM
总结以上是内存溢出为你收集整理的android – 当应用程序关闭或应用程序处于后台时,获取两次GCM PUSH通知全部内容,希望文章能够帮你解决android – 当应用程序关闭或应用程序处于后台时,获取两次GCM PUSH通知所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)