Android GCM应用程序在模拟器上工作,但不在真实设备上

时间:2015-03-06 18:16:11

标签: android android-emulator google-cloud-messaging

我正在开发一个聊天应用程序,它由两个Android应用程序组成,一个是服务器应用程序和客户端应用程序,但只有服务器应用程序发送数据和客户端应用程序接收它。我已经在模拟器上测试它一切正常,但是,当它在真实设备上进行了测试,服务器应用程序正在成功发送消息(我从服务器应用程序获得响应Result: [ messageId= 0:1425659852679944%ec35664638eb0007 ]),但它们在客户端应用程序上没有通知。

注意:没有后端服务器或sql数据库,现在只是复制客户端应用程序的注册ID并提供给应该发送消息的服务器应用程序。

请提前帮助解决此问题

我的客户端应用的清单文件

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

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


    <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" />

    <permission android:name="com.democlientapp.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.democlientapp.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"/>
        <activity android:name="com.google.android.gms.ads.AdActivity"
             android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>



        <activity
            android:name="com.democlientapp.RegisterActivity"
            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="com.democlientapp.MainActivity"
            android:label="@string/app_name" >

        </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.example.gcm" />
            </intent-filter>
        </receiver>
        <service android:name="com.democlientapp.GcmIntentService" />
    </application>

</manifest>

我的客户端应用程序的BroadcastReceiver.java

package com.democlientapp;

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

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("tag", "GcmBroadcastReceiver.java ok");
        // 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.java

package com.democlientapp;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GcmIntentService extends IntentService {
    public static  int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    String TAG="tag";
    SharedPreferences sp;
    StringBuffer sb;

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

    @Override
    protected void onHandleIntent(Intent intent) {
        String extras1 = intent.getExtras().getString("data");
        Log.i("tag", "string extras :"+extras1);
        Bundle extras=intent.getExtras();
        Log.i("tag", "bundle extras :"+extras.toString());

        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(1000);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                Log.i(TAG, "Received: " + extras.toString());
                // Post notification of received message.
                sendNotification("Received: " + extras);

            }
        }
        // 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) {
        Log.i("tag","GcmBroadcastReceiver.java send notification");


        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

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

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("Spy notification")
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg);

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

我的服务器应用程序代码,用于向Google服务器发送邮件

package com.application.service;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class ServerMsgs extends IntentService{

    public ServerMsgs() {
        super(ServerMsgs.class.getSimpleName());
        // TODO Auto-generated constructor stub
    }



String msg1;
SharedPreferences sp;

 static String API="AIzaSyA9G-pzEqVIT7am5IF9p_y0on0J_ViAwk";    


public String getTargetRegid(){
    String  name="MyPrefs";
     sp = this.getSharedPreferences(name, Context.MODE_PRIVATE);
    String prefName = sp.getString("CLIENTUSERNAME", "false");
    Log.i("tag","server.java, client regid is:  "+prefName);
    //String status="false";
    return prefName;


}


    @Override
    protected void onHandleIntent(Intent in) {
        // TODO Auto-generated method stub

         msg1=(String) in.getExtras().get("msg");



        try {
            //Please add here your project API key: "Key for browser apps (with referers)".
            //If you added "API key Key for server apps (with IP locking)" or "Key for Android apps (with certificates)" here
            //then you may get error responses.
            Sender sender = new  Sender(API);

            // use this to send message with payload data
            Message message = new Message.Builder()
            .collapseKey("message")
            .timeToLive(45)
            .delayWhileIdle(false)
            .addData(msg1, "") //you can get this message on client side app
            .build();  
            Log.i("tag", "server.java final message : "+message);

            //Use this code to send notification message to a single device
            //Result result = sender.send(message, getTargetRegid(),  1);
            Result result = sender.send(message,"APA91bF9VefxfRnAH_v20BMSNAhSUpqt2L5PbQYk2KhIiEniX5emx7SRsgcmFNGK4BPddLf99kxVr6Y8iopAh-apxcD46UEU8OJFnD3WsCKNZcIYAbGa5e3KM8SXG-3i8A02rCoOLgxGt-iW9TmZqtWzOiQovjbuIQ",  1);

            //System.out.println("Message Result: "+result.toString()); 
            Log.i("tag", "Message Result: "+result.toString());






        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

0 个答案:

没有答案