Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了android – 当应用程序关闭或应用程序处于后台时,获取两次GCM PUSH通知大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的应用程序中实现了gcm推送通知.一切都很好,我也收到通知.

问题:

>当应用程序处于后台或终止状态时,我一次收到2个通知.
>当应用程序处于前台时,只能获得我想要的1个通知.

我的代码如下:

用于接收消息的GCMPushReceiverservice类.

public class GCMPushReceiverservice extends GcmListenerservice {

//This method will be called on every new message received
@Override
public 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 front
private 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 = @L_75_9@manager.getDefaultUri(@L_75_9@manager.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 = @L_75_9@manager.getDefaultUri(@L_75_9@manager.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 errors
public 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 constructor
public GCMRegistrationIntentservice() {
    super("");
}


@Override
protected 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
@Override
protected 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
@Override
protected void onPause() {
    super.onPause();

LocalBroadcastManager.geTinstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);

}

android – 当应用程序关闭或应用程序处于后台时,获取两次GCM PUSH通知

android – 当应用程序关闭或应用程序处于后台时,获取两次GCM PUSH通知

解决方法

1.一旦从GCM收到消息,就会调用GCMPushReceiverservice类中的onmessageReceived函数.

用这个

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通知所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。