php - 无法使用 GCM 在 Android 设备中获取推送通知

标签 php android google-cloud-messaging

我正在编写代码,使用 GCM 从 php api 获取推送通知。从 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 权限

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

最佳答案

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

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>

对我有用

关于php - 无法使用 GCM 在 Android 设备中获取推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35285021/

相关文章:

javascript - Ajax/PHP 登录没有反应

java - 在退出时清理程序并处理 GC

java - 在android中绘制一个大尺寸的三角形imageview

java - 谷歌云消息 : Payload value always string

android - Android Nougat 通知的小图标不能使用黄色

python - __init__() 恰好接受 1 个参数(给定 3 个)Google 应用引擎

php - Mysql INSERT 在 PHP 中不起作用

php - GROUP BY 外键还是主键?

php - 在 Laravel 中验证 2 个数字的幂

android - Spring Android 连接被拒绝 ECONNREFUSED