GCM不可能收到消息 [英] GCM couldnt receive message

查看:118
本文介绍了GCM不可能收到消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器:

  VAR GCM =要求(GCM)GCM。

VAR apiKey ='XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
VAR GCM =新的GCM(apiKey);

VAR消息= {
    registration_id: 'APA91bEAjoFkJu6KF-UgbLWhB-qbHs6fHeYANpB1XFT4Y8NQbjaOJPQ_PItvBpPF5Zi3thEB6H-_0SXkT7JcYB4yGMOa-jZyeygkxTzy56bbqG8zqLSGouFpSr4F5uGvHzEywH_E3Lko8W57XiCe8F_NJGSvkA0i1jAvXkVvCYTzEyar-OAec10', // 需要
    collapse_key:折叠钥匙,
    data.key1:值1,
    data.key2:值2
};

gcm.send(消息功能(ERR,邮件ID){
    如果(ERR){
        的console.log(有些事情出了问题!);
    } 其他 {
        的console.log(送带消息ID:邮件ID);
    }
});
 

客户端:

 公共类GcmMessageHandler扩展IntentService {

     字符串MES;
     私人处理程序处理程序;
    公共GcmMessageHandler(){
        超级(GcmMessageHandler);
    }

    @覆盖
    公共无效的onCreate(){
        // TODO自动生成方法存根
        super.onCreate();
        处理程序=新的处理程序();
    }
    @覆盖
    保护无效onHandleIntent(意向意图){
        捆绑额外= intent.getExtras();

        GoogleCloudMessaging GCM = GoogleCloudMessaging.getInstance(本);
        //该getMessageType()的意图参数必须是您收到的意图
        //你的BroadcastReceiver。
        字符串为messageType = gcm.getMessageType(意向);

       MES = extras.getString(标题);
       showToast();
       Log.i(GCM,接收:(+为messageType +)+ extras.getString(标题));

        GcmBroadcastReceiver.completeWakefulIntent(意向);

    }

    公共无效showToast(){
        handler.post(新的Runnable(){
            公共无效的run(){
                Toast.makeText(getApplicationContext(),MES,Toast.LENGTH_LONG).show();
            }
         });

    }
}
 


 公共类GcmBroadcastReceiver扩展WakefulBroadcastReceiver {

    @覆盖
    公共无效的onReceive(上下文的背景下,意图意图){

        //明确指定GcmMessageHandler会处理这个意图。
        组件名补偿=新的组件名(context.getPackageName()
                GcmMessageHandler.class.getName());

        //启动服务,保持设备时推出清醒。
        startWakefulService(上下文,(intent.setComponent(化合物)));
        的setResult code(Activity.RESULT_OK);
    }
}
 

据昨天的工作,但现在不显示设备上的任何东西。我不知道自己做错了什么是。我没有改变任何东西。有人能对此有什么想法? (我的工作在真实设备上)

编辑:

它可以在模拟器。

清单:

  

 <使用-SDK
    安卓的minSdkVersion =8
    机器人:targetSdkVersion =17/>

<使用-权限的Andr​​oid:名称=android.permission.INTERNET对/>
<使用-权限的Andr​​oid:名称=android.permission.GET_ACCOUNTS/>
<使用-权限的Andr​​oid:名称=android.permission.WAKE_LOCK/>
<使用-权限的Andr​​oid:名称=com.google.android.c2dm.permission.RECEIVE/>
 

     

 <应用

    机器人:allowBackup =真
    机器人:图标=@可绘制/ ic_launcher
    机器人:标签=@字符串/ APP_NAME
    机器人:主题=@风格/ AppTheme
    >
    <活动
        机器人:名称=com.hmk code.android.gcm.MainActivity
        机器人:标签=@字符串/ APP_NAME>
        <意向滤光器>
            <作用机器人:名称=android.intent.action.MAIN/>

            <类机器人:名称=android.intent.category.LAUNCHER/>
        &所述; /意图滤光器>
    < /活性GT;
    <接收器
        机器人:名称=。GcmBroadcastReceiver
        机器人:权限=com.google.android.c2dm.permission.SEND>
        <意向滤光器>
            <作用机器人:名称=com.google.android.c2dm.intent.RECEIVE/>
            <类机器人:名称=com.hmk code.android.gcm/>
        &所述; /意图滤光器>
    < /接收器>
    <服务机器人:名称=。GcmMessageHandler/>

    <元数据的android:NAME =com.google.android.gms.version
       机器人:值=@整数/ google_play_services_version/>
< /用途>
 

     

解决方案

检查这code这可能会帮助你:

 保护无效GCM(){
    // TODO自动生成方法存根
    GCMHelper gcmhelper =新GCMHelper();
    串gcmtokenAlready = gcmhelper.alreadyregisterGCM();
    如果(gcmtokenAlready.length()大于0){

        在这里做code

    }其他{
        gcmhelper.registerGCM();
    }
 

// GCMHelper

 公共类GCMHelper {
。私人最终字符串SENDER_ID = ContextProvider.getContext()getResources()的getString(R.string.GCM_ID)。
私人最终上下文语境= ContextProvider.getContext();
/ **
 *此方法用于注册设备的GCM。
 *
 *参数上下文语境
 * /
公共无效registerGCM(){
    GCMRegistrar.checkDevice(上下文);
    GCMRegistrar.checkManifest(上下文);
    GCMRegistrar.register(背景下,SENDER_ID);
}

/ **
 *已经注册GCM。
 *
 *参数上下文语境
 返回:字符串
 * /
公共字符串alreadyregisterGCM(){
    GCMRegistrar.checkDevice(上下文);
    GCMRegistrar.checkManifest(上下文);
    返回GCMRegistrar.getRegistrationId(上下文);
}
 

}

// GCMIntentService
//注意将这个类在应用程序的主包。

 公共类GCMIntentService扩展GCMBaseIntentService {

/ **
 *实例化一个新的GCM意图服务。
 * /
公共GCMIntentService(){
    超(。ContextProvider.getContext()getResources()的getString(R.string.GCM_ID));
}

/ *
 *(非Javadoc中)
 *
 * @看到
 * com.google.android.gcm.GCMBaseIntentService#的onError(android.content.Context
 *,java.lang.String中)
 * /
@覆盖
保护无效的onError(背景为arg0,串ARG1){
    // TODO自动生成方法存根
    Log.d(TAG,错误:+sError);
}

/ *
 * @see时使用的信息,那就形式GCM服务器。请致电您的通知
 *此处类
 * /

/ *(非Javadoc中)
 * @see com.google.android.gcm.GCMBaseIntentService#的onMessage(android.content.Context,android.content.Intent)
 * /
@覆盖
保护无效的onMessage(上下文的背景下,意图ARG1){
    // TODO自动生成方法存根
    字符串notiData = arg1.getStringExtra(信息);
    / **开始播放* /
    意图mintent =新的意向书(PAYMENT_STATUS_MESSAGE);
    mintent.putExtra(PAYMENT_STATUS_MESSAGE,notiData);
    //发送广播
    sendBroadcast(mintent);
    //生成通知
    generateNotification(背景下,notiData);
}

/ *
 *(非Javadoc中)
 *
 * @看到
 * com.google.android.gcm.GCMBaseIntentService#onRegistered(android.content
 * .Context,java.lang.String中)
 * /
@覆盖
保护无效onRegistered(上下文的背景下,字符串令牌){
    / **保存设备令牌应用程序类* /
    Log.v(TAG,注册第一时间);

}


/ *(非Javadoc中)
 * @see com.google.android.gcm.GCMBaseIntentService#onUnregistered(android.content.Context,java.lang.String中)
 * /
@覆盖
保护无效onUnregistered(背景为arg0,串ARG1){}

/ **
 *问题的通知,通知服务器发送邮件的用户。
 *
 *参数上下文语境
 * @参数消息的消息
 * /
私人无效generateNotification(上下文的背景下,字符串消息){
    时长= System.currentTimeMillis的();
    NotificationManager notificationManager =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    通知通知=新的通知(R.drawable.ic_launcher,消息的时候);
    字符串标题=新POC警报;
    意图notificationIntent =新的意图(背景下,NULL);
    //设置的意图,因此它不会开始一个新的活动
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent意图= PendingIntent.getActivity(上下文,0,notificationIntent,0);
    notification.setLatestEventInfo(背景下,标题,邮件,意图);
    notification.flags | = Notification.FLAG_AUTO_CANCEL;

    //播放默认通知声音
    notification.defaults | = Notification.DEFAULT_SOUND;

    //如果振动被启用时振动
    notification.defaults | = Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0,通知);
}
 

}

// Mainfest配置

 <! -  GCM权限 - >
<使用-权限的Andr​​oid:名称=android.permission.GET_ACCOUNTS/>
<使用-权限的Andr​​oid:名称=android.permission.WAKE_LOCK/>
<使用-权限的Andr​​oid:名称=com.google.android.c2dm.permission.RECEIVE/>
<使用-权限的Andr​​oid:名称=android.permission.VIBRATE/>
 <许可
    机器人:名称=com.sc.candidate.permission.C2D_MESSAGE
    安卓的ProtectionLevel =签名/>

<使用-权限的Andr​​oid:名称=com.sc.candidate.permission.C2D_MESSAGE/>
<使用-权限的Andr​​oid:名称=com.google.android.c2dm.permission.RECEIVE/>
<使用-权限的Andr​​oid:名称=震动/>

  <! - 对于GCM  - >
    <接收器
        机器人:名称=com.google.android.gcm.GCMBroadcastReceiver
        机器人:权限=com.google.android.c2dm.permission.SEND>
        <意向滤光器>
            <作用机器人:名称=com.google.android.c2dm.intent.RECEIVE/>
            <作用机器人:名称=com.google.android.c2dm.intent.REGISTRATION/>

            <类机器人:名称=com.sc.candidate/>
        &所述; /意图滤光器>
    < /接收器>

    <服务机器人。GCMIntentServiceNAME = />
 

*请注意,请更改包的名称根据您的应用程序主包。

Server:

var GCM = require('gcm').GCM;

var apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var gcm = new GCM(apiKey);

var message = {
    registration_id: 'APA91bEAjoFkJu6KF-UgbLWhB-qbHs6fHeYANpB1XFT4Y8NQbjaOJPQ_PItvBpPF5Zi3thEB6H-_0SXkT7JcYB4yGMOa-jZyeygkxTzy56bbqG8zqLSGouFpSr4F5uGvHzEywH_E3Lko8W57XiCe8F_NJGSvkA0i1jAvXkVvCYTzEyar-OAec10', // required
    collapse_key: 'Collapse key', 
    'data.key1': 'value1',
    'data.key2': 'value2'
};

gcm.send(message, function(err, messageId){
    if (err) {
        console.log("Something has gone wrong!");
    } else {
        console.log("Sent with message ID: ", messageId);
    }
});

Client :

public class GcmMessageHandler extends IntentService {

     String mes;
     private Handler handler;
    public GcmMessageHandler() {
        super("GcmMessageHandler");
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        handler = new Handler();
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();

        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

       mes = extras.getString("title");
       showToast();
       Log.i("GCM", "Received : (" +messageType+")  "+extras.getString("title"));

        GcmBroadcastReceiver.completeWakefulIntent(intent);

    }

    public void showToast(){
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(),mes , Toast.LENGTH_LONG).show();
            }
         });

    }
}


public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // Explicitly specify that GcmMessageHandler will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmMessageHandler.class.getName());

        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

It worked yesterday, but now it does not show anything on a device. I have no idea what wrong is. I didn't change anything. Can someone have any idea about it? (I am working on a real device)

EDIT:

It works on emulator.

MANIFEST:

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />     

<application

    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" 
    >
    <activity
        android:name="com.hmkcode.android.gcm.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver
        android:name=".GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.hmkcode.android.gcm" />
        </intent-filter>
    </receiver>
    <service android:name=".GcmMessageHandler" />

    <meta-data android:name="com.google.android.gms.version"
       android:value="@integer/google_play_services_version" />
</application>

解决方案

Check This code It may be help you :

protected void gcm() {
    // TODO Auto-generated method stub
    GCMHelper gcmhelper = new GCMHelper();
    String gcmtokenAlready = gcmhelper.alreadyregisterGCM();
    if(gcmtokenAlready.length()>0){

        To do code here

    }else{
        gcmhelper.registerGCM();
    }

//GCMHelper

public class GCMHelper {
private final String SENDER_ID = ContextProvider.getContext().getResources().getString(R.string.GCM_ID);
private final Context context = ContextProvider.getContext();
/**
 *  This method is used to register the device with the GCM.
 *
 * @param context the context
 */
public void registerGCM() {
    GCMRegistrar.checkDevice(context);
    GCMRegistrar.checkManifest(context);        
    GCMRegistrar.register(context, SENDER_ID);
}

/**
 * Already register gcm.
 *
 * @param context the context
 * @return the string
 */
public String alreadyregisterGCM() {
    GCMRegistrar.checkDevice(context);
    GCMRegistrar.checkManifest(context);
    return GCMRegistrar.getRegistrationId(context);
}

}

//GCMIntentService
//Note Put this class in main package of your Application.

public class GCMIntentService extends GCMBaseIntentService {

/**
 * Instantiates a new GCM intent service.
 */
public GCMIntentService() {
    super(ContextProvider.getContext().getResources().getString(R.string.GCM_ID));
}

/*
 * (non-Javadoc)
 * 
 * @see
 * com.google.android.gcm.GCMBaseIntentService#onError(android.content.Context
 * , java.lang.String)
 */
@Override
protected void onError(Context arg0, String arg1) {
    // TODO Auto-generated method stub
    Log.d(TAG, "Error: " + "sError");
}

/*
 * @see Used when message comes form GCM server. Call your notification
 * class here
 */

/* (non-Javadoc)
 * @see com.google.android.gcm.GCMBaseIntentService#onMessage(android.content.Context, android.content.Intent)
 */
@Override
protected void onMessage(Context context, Intent arg1) {
    // TODO Auto-generated method stub
    String notiData = arg1.getStringExtra("message");
    /**Start BroadCast*/
    Intent mintent = new Intent("PAYMENT_STATUS_MESSAGE");
    mintent.putExtra("PAYMENT_STATUS_MESSAGE", notiData);
    //Send BroadCast
    sendBroadcast(mintent);
    //Generate Notification
    generateNotification(context, notiData);
}

/*
 * (non-Javadoc)
 * 
 * @see
 * com.google.android.gcm.GCMBaseIntentService#onRegistered(android.content
 * .Context, java.lang.String)
 */
@Override
protected void onRegistered(Context context, String token) {
    /** Saving the device token in the Application Class */
    Log.v(TAG, "Registered First Time");

}


/* (non-Javadoc)
 * @see com.google.android.gcm.GCMBaseIntentService#onUnregistered(android.content.Context, java.lang.String)
 */
@Override
protected void onUnregistered(Context arg0, String arg1) { }

/**
 * Issues a notification to inform the user that server has sent a message.
 *
 * @param context the context
 * @param message the message
 */
private void generateNotification(Context context, String message) {
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)   context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.ic_launcher, message, when);         
    String title = "New POC Alert";         
    Intent notificationIntent = new Intent(context, null);
    // 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, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);
}

}

//Mainfest Config

  <!-- GCM Permission -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.VIBRATE" />
 <permission
    android:name="com.sc.candidate.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.sc.candidate.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="vibrate" />

  <!-- For GCM -->
    <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.sc.candidate" />
        </intent-filter>
    </receiver>

    <service android:name=".GCMIntentService" />

*Note please change the package name According to your application main package.

这篇关于GCM不可能收到消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆