接收Android通知

时间:2014-03-12 20:22:34

标签: android notifications push-notification broadcastreceiver google-cloud-messaging

我已关注this文档,以便能够收到GCM通知。 这是我的清单:

<uses-sdk
    android:minSdkVersion="12"
    android:targetSdkVersion="18" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />
<uses-feature android:name="android.hardware.camera" />

<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" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<permission
    android:name="com.example.gcm.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

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

<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" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="@string/google_android_api_key" />

    <activity
        android:name="com.evapp.activities.SplashActivity"
        android:label="@string/title_activity_splash" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.evapp.activities.LoginActivity"
        android:label="@string/title_activity_login" >
    </activity>
    <activity
        android:name="com.evapp.activities.RegistrationActivity"
        android:label="@string/title_activity_signup"
        android:parentActivityName="com.evapp.activities.LoginActivity" >

        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.evapp.activities.LoginActivity" />
    </activity>
    <activity
        android:name="com.evapp.activities.HomeActivity"
        android:label="@string/title_activity_home" >
    </activity>
    <activity
        android:name="com.evapp.activities.UserActivity"
        android:label="@string/title_activity_user" >
    </activity>
    <activity
        android:name="com.evapp.activities.TestActivity"
        android:label="@string/title_activity_test" >
    </activity>

    <receiver
        android:name="com.evapp.notification.Test"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <category android:name="com.evapp.notification" />
        </intent-filter>
    </receiver>

    <service android:name="com.evapp.activities.GcmIntentService" />
</application>

这里是WakefulBroadcastReceiver

public class Test extends WakefulBroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent gcmIntent = new Intent(context, GcmIntentService.class);
        gcmIntent.putExtras(intent.getExtras());
        startWakefulService(context, gcmIntent);
        setResultCode(Activity.RESULT_OK);
    }

}

IntentService

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

    public GcmIntentService()
    {
        super("GcmIntentService");
    }

    @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++)
                {

                    try
                    {
                        Thread.sleep(5000);
                    } 
                    catch (InterruptedException e)
                    {
                    }
                }
                // Post notification of received message.
                sendNotification("Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        Test.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, HomeActivity.class), 0);

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

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

从我的服务器端,我得到了这个回复:

{"multicast_id":7269872883857375111,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1394655370108962%e210e99800364492"}]}

但是在调试时我从未进入GcmIntentService,调试器进入Test类并且没有任何反应。

我错过了什么?似乎startWakefulService没有打开GcmIntentService

注意: 我已经改变了@Eran建议的代码(仍然没有工作:()

1 个答案:

答案 0 :(得分:2)

ComponentName comp = new ComponentName(context.getPackageName(),
                                       GcmIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));

这只适用于您的GCMIntentService类位于应用程序的主程序包中的情况,我认为不是这种情况(因为您的接收器类位于不同的程序包中com.evapp.notification - 而不是您的主程序包app - com.evapp.activities)。

您可以尝试这样的事情:

Intent gcmIntent = new Intent(context, GcmIntentService.class);
gcmIntent.putExtras(intent.getExtras());
startWakefulService(context, gcmIntent);