GCM推送通知未收到

时间:2015-10-06 13:19:01

标签: android broadcastreceiver google-cloud-messaging android-permissions

我是android的新手。我正在使用GCM实现推送通知。我已经完成了所有事情,比如在控制台中创建项目并生成SENDER_ID和API密钥以及生成注册ID等。但最后通知未收到.Below是我的代码

GCMBroadcastReciever.java

package com.devpoint.rprtjobs;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class GCMBroadcastReceiver extends WakefulBroadcastReceiver { 

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            ComponentName comp = new ComponentName(context.getPackageName(),
                    GCMIntentService.class.getName());
            startWakefulService(context, (intent.setComponent(comp)));
            setResultCode(Activity.RESULT_OK);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
}

GCMIntentService.Java

package com.devpoint.rprtjobs;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

import com.devpoint.rprtgnet.LoadActivity;
import com.devpoint.rprtjobs.R;

public class GCMIntentService extends IntentService {
    // Sets an ID for the notification, so it can be updated
    public static final int notifyID = 112;
    //NotificationCompat.Builder builder;
    private static int numMessagesTwo = 0;
    //private JSONObject SaveOfferObj;

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

    @Override
    protected void onHandleIntent(Intent intent) {

        try {
            String message = intent.getExtras().getString(getString(R.string.gcm_msg));
            String FromDeviceId = intent.getExtras().getString(getString(R.string.FromDeviceId));
            String ToDeviceId = intent.getExtras().getString(getString(R.string.ToDeviceId));
            String GCM_Regid = intent.getExtras().getString(getString(R.string.GCM_Regid));
            String UserName = intent.getExtras().getString(getString(R.string.Chat_UserName));
            if(ToDeviceId!= null)
            {
                sendNotification(message, UserName , FromDeviceId , ToDeviceId , GCM_Regid);
            }

            GCMBroadcastReceiver.completeWakefulIntent(intent);
        } catch (Exception e) {
            //PostLogcatErorrs(e);
            e.printStackTrace();
        }
    }


    private void sendNotification(String message , String UserName, String FromDeviceId , String  ToDeviceId ,  String GCM_Regid) {



        try { 
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    this);
            mBuilder.setContentTitle(UserName);
            mBuilder.setTicker(UserName + " : New Notification  Received!");

             mBuilder.setSmallIcon(R.drawable.ic_launcher);
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            String[] events = new String[4];
            events[0] = "1) " + FromDeviceId;
            events[1] = "2) " + ToDeviceId;
            events[2] = "3) " + GCM_Regid;
            events[3] = "3) " + message;

            inboxStyle.setBigContentTitle(getString(R.string.sendnoti_title));
            for (String event : events) {
                inboxStyle.addLine(event);
            }
            mBuilder.setStyle(inboxStyle);
            mBuilder.setNumber(++numMessagesTwo);
            mBuilder.setAutoCancel(true);
            Intent resultIntent = new Intent(this, LoadActivity.class);

            resultIntent.putExtra("username",   UserName);
            //resultIntent.putExtra(getString(R.string.gcm_push),   getString(R.string.gcm_username));
            resultIntent.putExtra("FromDeviceId",   FromDeviceId);
            resultIntent.putExtra("ToDeviceId",ToDeviceId);
            resultIntent.putExtra("GCM_Regid", GCM_Regid);
            resultIntent.putExtra("UserName", UserName);
            resultIntent.putExtra("PageName", "SplashScreen");
            resultIntent.putExtra("message" ,message);


            resultIntent.putExtra(getString(R.string.gcm_push) ,message);       
            resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);

            int defaults = 0;
            defaults = defaults | Notification.DEFAULT_LIGHTS;
            defaults = defaults | Notification.DEFAULT_VIBRATE;
            defaults = defaults | Notification.DEFAULT_SOUND;

            mBuilder.setDefaults(defaults);

            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(LoadActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
            mBuilder.setContentIntent(resultPendingIntent);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(notifyID, mBuilder.build());
        } catch (Exception e) {
            //PostLogcatErorrs(e);
            e.printStackTrace();
        }

    }
}

这是我的服务器端代码

string GoogleAppID = "XXXXXXXXXXX";   //from console
                string SENDER_ID = "XXXXXXXXXX";  //from console
                string regid = MsgObj.GCM_Regid;// Registered from mobile
                WebRequest tRequest;
                tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
                tRequest.Method = "post";
                tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
                tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID)); 
                tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));


                string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.OpportunityName=" + MsgObj.OpportunityName
                                                                                                             + " &data.OpportunityKeywords=" + MsgObj.OpportunityKeywords
                                                                                                              + "&data.StartDate=" + MsgObj.StartDate
                                                                                                              + "&data.GCM_Regid=" + MsgObj.GCM_Regid
                                 + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + regid + "";
                Console.WriteLine(postData);
                Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                tRequest.ContentLength = byteArray.Length;
                Stream dataStream = tRequest.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                WebResponse tResponse = tRequest.GetResponse();
                dataStream = tResponse.GetResponseStream();
                StreamReader tReader = new StreamReader(dataStream);
                String sResponseFromServer = tReader.ReadToEnd();
                tReader.Close();
                dataStream.Close();
                tResponse.Close();

注册时的senderid与上述代码中的相同。

清单文件

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" /> 
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <permission
        android:name="com.devpoint.rprtjobs.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="com.devpoint.rprtjobs.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!--
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    -->
    <uses-permission android:name="android.permission.READ_PHONE_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.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

这是我在Manifest中的接收者

<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.devpoint.rprtjobs" /> 
            </intent-filter>
        </receiver>

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

请建议我问题出在哪里..谢谢你提前This is my logcat

以上是我的logcat

0 个答案:

没有答案