无法使用GCM在Android设备中获取推送

时间:2016-02-09 06:06:51

标签: php android google-cloud-messaging

我正在编写一个代码,用于从php api使用GCM获取推送通知。从PHP方面我获得了成功,但在Android设备上我没有得到任何通知。这是我正在使用的代码

import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

    private static final String TAG = "GCM Tutorial::Service";

    // Use your PROJECT ID from Google API into SENDER_ID
    public static final String SENDER_ID = "394127269050";

    public GCMIntentService() {
        super(SENDER_ID);
    }

    @Override
    protected void onRegistered(Context context, String registrationId) {

        Log.i(TAG, "onRegistered: registrationId=" + registrationId);
    }

    @Override
    protected void onUnregistered(Context context, String registrationId) {

        Log.i(TAG, "onUnregistered: registrationId=" + registrationId);
    }

    @Override
    protected void onMessage(Context context, Intent data) {
        String message;
        // Message from PHP server
        message = data.getStringExtra("message");
        // Open a new activity called GCMMessageView
        Intent intent = new Intent(this, GCMMessageView.class);
        // Pass data to the new activity
        intent.putExtra("message", message);
        // Starts the activity on notification click
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        // Create the notification with a notification builder
        Notification notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .setContentTitle("Android GCM Tutorial")
                .setContentText(message).setContentIntent(pIntent)
                .getNotification();
        // Remove the notification on click
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(R.string.app_name, notification);

        {
            // Wake Android Device when notification received
            PowerManager pm = (PowerManager) context
                    .getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock mWakelock = pm.newWakeLock(
                    PowerManager.FULL_WAKE_LOCK
                            | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
            mWakelock.acquire();

            // Timer before putting Android Device to sleep mode.
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                public void run() {
                    mWakelock.release();
                }
            };
            timer.schedule(task, 5000);
        }

    }

    @Override
    protected void onError(Context arg0, String errorId) {

        Log.e(TAG, "onError: errorId=" + errorId);
    }

}

AndroidManifiest Permissions

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

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

2 个答案:

答案 0 :(得分:1)

您必须像这样创建一个广播接收器

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

/**
 * Created by rushabh on 1/9/15.
 */
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);

      /*  Intent i=new Intent(context,DialogActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);*/
    }
}

复制此课程

     public class GcmMessageHandler extends IntentService {

             String mes;
            private Handler handler;
            Context context = this;
            String user;
            PowerManager pm ;
            String phn;
            boolean isScreenOn;
            public GcmMessageHandler() {
                super("GcmMessageHandler");
            }
            SharedPreferences preferences;
            SharedPreferences.Editor editor;
            @Override
            public void onCreate() {
                // TODO Auto-generated method stub
                super.onCreate();
                handler = new Handler();
                pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
                isScreenOn = pm.isScreenOn();

            }
            @Override
            protected void onHandleIntent(Intent intent) {
                Bundle extras = intent.getExtras();

                GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

                String messageType = gcm.getMessageType(intent);

    //get your message here

                mes = extras.getString("your String");

                user=extras.getString("your String");
             //Show Your Local Notification
               notification();
                             if (isScreenOn == false) {
                                PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
                                wl.acquire(10000);
                                PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
                                wl_cpu.acquire(10000);
                           }
               GcmBroadcastReceiver.completeWakefulIntent(intent);

                }

在AndroidManifest中声明它

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

为我工作

答案 1 :(得分:0)

您是否在项目中添加了接收器类,清单中的接收器标签?

<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="example.demo.customer" />
        </intent-filter>
    </receiver>

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