Android GCM服务器已发送,但GCM未推送至设备 [英] Android GCM server sent but GCM not pushing to device

查看:82
本文介绍了Android GCM服务器已发送,但GCM未推送至设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在手机上测试GCM。 (2.3.6 android)。
$ b

清单文件(MainActivity,First和Second activity不做任何事情,它们用于其他测试目的,不干扰GCM) 。

 <?xml version =1.0encoding =utf-8?> 
< manifest xmlns:android =http://schemas.android.com/apk/res/android
package =com.example.testconnectionapp
android:versionCode = 1
android:versionName =1.0>

<使用权限android:name =android.permission.INTERNET/>
<使用权限android:name =android.permission.READ_CONTACTS/>
<! - GCM需要Google帐户。 - >
<使用权限android:name =android.permission.GET_ACCOUNTS/>
<! - 保持处理器在收到消息时不会睡眠。 - >
<使用权限android:name =android.permission.WAKE_LOCK/>
<! -
创建一个自定义权限,所以只有这个应用程序可以接收它的消息。

注意:权限*必须*称为PACKAGE.permission.C2D_MESSAGE,
其中PACKAGE是应用程序的包名。
- >
< permission
android:name =com.example.testconnectionapp.permission.C2D_MESSAGE
android:protectionLevel =signature/>

<使用权限android:name =com.example.testconnectionapp.permission.C2D_MESSAGE/>

<! - 这个应用程序有权注册和接收数据信息。 - >
< uses-permission android:name =com.google.android.c2dm.permission.RECEIVE/>

< uses-sdk
android:minSdkVersion =10
android:targetSdkVersion =21/>

< application
android:allowBackup =true
android:icon =@ drawable / ic_launcher
android:label =@ string / app_name
android:theme =@ style / AppTheme>
< meta-data
android:name =com.google.android.gms.version
android:value =@ integer / google_play_services_version/>

< activity
android:name =。DemoActivity
android:label =@ string / app_name
android:configChanges =orientation | keyboardHidden | screenSize
android:launchMode =singleTop>
< intent-filter>

< category android:name =android.intent.category.LAUNCHER/>
< / intent-filter>
< / activity>

< receiver
android:name =。GcmBroadcastReceiver
android:permission =com.google.android.c2dm.permission.SEND>
< intent-filter>
<! - 接收实际的信息。 - >
< category android:name =com.google.android.gcm.demo.app/>
< / intent-filter>
< / receiver>
< service android:name =.GcmIntentService/>

< activity
android:name =。MainActivity
android:label =@ string / app_name>
<! - < intent-filter>

< category android:name =android.intent.category.LAUNCHER/>
< / intent-filter> - >
< / activity>
< activity
android:name =。First
android:label =@ string / title_activity_first>
< / activity>
< activity
android:name =。Second
android:label =@ string / title_activity_second>
< / activity>
< activity
android:name =。SQLiteCrudExample
android:label =@ string / title_activity_second>
< / activity>
< / application>

< / manifest>

GCMBroadcastReceiver

  public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context,Intent intent){
//明确指定GcmIntentService将处理意图。
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
//启动服务,保持设备在启动时保持清醒状态。
startWakefulService(context,(intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);


GCMIntentSErvice

  public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder构建器;

public GcmIntentService(){
super(GcmIntentService);
}
public static final String TAG =GCM Demo;

@Override
protected void onHandleIntent(Intent intent){
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// getMessageType()意图参数必须是您在BroadcastReceiver中收到
//的意图。
字符串messageType = gcm.getMessageType(intent);

if(!extras.isEmpty()){//具有不合格的效果Bundle
/ *
*根据消息类型过滤消息。由于GCM很可能在未来使用新的消息类型进行
*扩展,因此忽略任何您感兴趣的消息类型或您不认识的消息类型。
* /
if(GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)){
sendNotification(Send error:+ extras.toString());
} else if(GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)){
sendNotification(服务器上的已删除邮件:+ extras.toString());
//如果是常规的GCM消息,请做一些工作。
} else if(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)){
//此循环表示服务正在进行一些工作。 (标记i = 0; i <5; i ++){
Log.i(标记,正在工作...+(i + 1)
+/ 5 @ + SystemClock.elapsedRealtime());
尝试{
Thread.sleep(5000);
} catch(InterruptedException e){
}
}
Log.i(TAG,Completed work @+ SystemClock.elapsedRealtime());
//发送收到的消息通知。
sendNotification(Received:+ extras.toString());
Log.i(TAG,Received:+ extras.toString());
}
}
//释放由WakefulBroadcastReceiver提供的唤醒锁。
GcmBroadcastReceiver.completeWakefulIntent(intent);
}

//将消息放入通知中并发布。
//这只是您可能选择使用
// GCM消息做的一个简单示例。
private void sendNotification(String msg){
mNotificationManager =(NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);

PendingIntent contentIntent = PendingIntent.getActivity(this,0,
new Intent(this,DemoActivity.class),0);

NotificationCompat.Builder mBuilder =
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.abc_ab_solid_dark_holo)
.setContentTitle(GCM Notification)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);

mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID,mBuilder.build());






$ b现在,我可以从服务器发送消息显示


将POST请求发送至网址:
https://android.googleapis.com/gcm/send 响应码:200
{multicast_id:5410443299609525979,success:1,失败:0,canonical_ids:0,results:[{message_id:0:1409160055237618%a13ced80f9fd7ecd}]}

但在此之后,我看不到在我的手机上生成通知。这里发生了什么。这可能是什么原因?

我连接到家里的wifi,我的手机上也有激活的数据包,所以即使我解散了wifi (不知道为什么这会影响,但解决方案这里建议),但仍然没有收到任何通知。



任何帮助将不胜感激。 您的接收器中存在错误的类别(< category android:name =com。 google.android.gcm.demo.app/> )。将其更改为 com.example.testconnectionapp ,假设这是您应用的软件包名称。


I am testing GCM on my cell phone. (2.3.6 android).

Manifest file (MainActivity, First and Second activity do not do anything, they are there for some other testing purpose, not interfering with GCM).

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testconnectionapp"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!--
 Creates a custom permission so only this app can receive its messages.

 NOTE: the permission *must* be called PACKAGE.permission.C2D_MESSAGE,
       where PACKAGE is the application's package name.
-->
<permission
    android:name="com.example.testconnectionapp.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.testconnectionapp.permission.C2D_MESSAGE" />

<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".DemoActivity"
        android:label="@string/app_name"
        android:configChanges="orientation|keyboardHidden|screenSize"
            android:launchMode="singleTop">
        <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>
            <!-- Receives the actual messages. -->
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.google.android.gcm.demo.app" />
        </intent-filter>
    </receiver>
    <service android:name=".GcmIntentService" />

    <activity
        android:name=".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>
    <activity
        android:name=".First"
        android:label="@string/title_activity_first" >
    </activity>
    <activity
        android:name=".Second"
        android:label="@string/title_activity_second" >
    </activity>
    <activity
        android:name=".SQLiteCrudExample"
        android:label="@string/title_activity_second" >
    </activity>
</application>

</manifest>

GCMBroadcastReceiver

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // Explicitly specify that GcmIntentService will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(),
            GcmIntentService.class.getName());
    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}
}

GCMIntentSErvice

public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;

public GcmIntentService() {
    super("GcmIntentService");
}
public static final String TAG = "GCM Demo";

@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);

    if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " + extras.toString());
        // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // This loop represents the service doing some work.
            for (int i = 0; i < 5; i++) {
                Log.i(TAG, "Working... " + (i + 1)
                        + "/5 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            sendNotification("Received: " + extras.toString());
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, DemoActivity.class), 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.abc_ab_solid_dark_holo)
    .setContentTitle("GCM Notification")
    .setStyle(new NotificationCompat.BigTextStyle()
    .bigText(msg))
    .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}

Now, I can send the message from server as it shows

Sending 'POST' request to URL : https://android.googleapis.com/gcm/send Response Code : 200 {"multicast_id":5410443299609525979,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1409160055237618%a13ced80f9fd7ecd"}]}

But after that I do not see the notification getting generated on my phone. What is happening here. What could be the possible reasons for this?

I am connected to the wifi at home, also I have data pack activated on my phone, so even if I disconnet the wifi (not sure why that would impact anyway, but the solution here suggested) but still I am not getting any notification generated.

Any help will be highly appreciated.

解决方案

You got the wrong category in your receiver (<category android:name="com.google.android.gcm.demo.app" />). Change it to com.example.testconnectionapp, assuming that's your app's package name.

这篇关于Android GCM服务器已发送,但GCM未推送至设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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