2016年未弃用的GCM Cloud Endpoints示例

时间:2016-03-04 21:27:20

标签: android google-app-engine google-cloud-messaging google-cloud-endpoints

去年,当您将一个Cloud Endpoints plus GCM模块添加到Android Studio项目时,IDE在backendapp中创建了一些示例代码,展示了如何将GCM与Cloud Endpoints结合使用

但是,对于较新版本的Android Studio,您只能为您添加backend部分。所以我回到了我的旧项目中,挖出了一些方便的app代码,这些代码已注册,并在Android中发送了GCM推送通知。

以下是代码的样子:

GcmBroadcastReceiver.java

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 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

public class GcmIntentService extends IntentService {

    android.support.v4.app.NotificationCompat.Builder notification;

    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 != null && !extras.isEmpty()) {  // has effect of unparcelling Bundle
            // Since we're not using two way messaging, this is all we really to check for
            if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                Logger.getLogger("GCM_RECEIVED").log(Level.INFO, extras.toString());

                showToast(extras.getString("message"));
                sendNotification(extras.getString("message"));

            }
        }

        //call to the API and get new data.

        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    protected void showToast(final String message) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }

    private void sendNotification(String msg) {
        notification = new android.support.v4.app.NotificationCompat.Builder(this);
        //set number of notifications count
        //notification.setNumber(x);
        //cancels notification when app is opened.
        notification.setAutoCancel(true);
        //build the notification
        notification.setSmallIcon(R.drawable.greenicon);
        notification.setTicker("This is the ticker!");
        //set time
        notification.setWhen(System.currentTimeMillis());
        notification.setContentTitle("New message!");
        notification.setContentText(msg);
        notification.setSound((Settings.System.DEFAULT_NOTIFICATION_URI));
        //LED
        notification.setLights(Color.RED, 3000, 3000);
        // intent
        Intent intent = new Intent(this, MainActivity.class);
        //give phone access to perform this intent b/c they may be in another part of their phone.
        //aka gives phone access to the intents in our app
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //what to do when notification is clicked:
        notification.setContentIntent(pendingIntent);

        //Builds notification and issues it (sends it to device). Can build and send out notifcations
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //send out notification with uniqueID
        nm.notify(2158, notification.build());
    }
}

GcmRegistrationAsyncTask

class GcmRegistrationAsyncTask extends AsyncTask<Void, Void, String> {
    private static Registration regService = null;
    private GoogleCloudMessaging gcm;
    private Context context;

    // TODO: change to your own sender ID to Google Developers Console project number, as per instructions above
    private static final String SENDER_ID = "1026567774990";

    public GcmRegistrationAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(Void... params) {
        if (regService == null) {
            Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(),
                    new AndroidJsonFactory(), null)
                    // Need setRootUrl and setGoogleClientRequestInitializer only for local testing,
                    // otherwise they can be skipped
                    .setRootUrl("https://push-notif-45657747.appspot.com/_ah/api/")
                    .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                        @Override
                        public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest)
                                throws IOException {
                            abstractGoogleClientRequest.setDisableGZipContent(true);
                        }
                    }) ;
            // end of optional local run code

            regService = builder.build();
        }

        String msg = "";
        try {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(context);
            }
            String regId = gcm.register(SENDER_ID);
            msg = "Device registered, registration ID=" + regId;

            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.
            regService.register(regId).execute();

        } catch (IOException ex) {
            ex.printStackTrace();
            msg = "Error: " + ex.getMessage();
        }
        return msg;
    }

    @Override
    protected void onPostExecute(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        Logger.getLogger("REGISTRATION").log(Level.INFO, msg);
    }
}

但是,我现在在Android Studio中收到了一些已弃用的错误:

不推荐使用

gcm.register(SENDER_ID);GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE也是如此。

这个GCM的东西开头很混乱,虽然有一些关于如何使用它的信息here,但我想知道是否有人有任何当前正在使用的非弃用示例,或者你可能会建议一些编辑上面的代码,如果你知道你在做什么......?非常感谢!

1 个答案:

答案 0 :(得分:0)

想要给人们一些指导,以防他们迷路。

首先查看并了解此Google Cloud Messaging Android示例:

https://github.com/google/gcm

要使其正常工作,您必须生成google-services.json文件,您可以在此处执行此操作: https://developers.google.com/mobile/add

确保在转到该链接之前登录Google开发者控制台。它将为您加载项目,并在项目凭据中自动为您设置gcm api密钥。

google-services.json复制/粘贴到Android项目的/app目录中。

将带有gcm模块的云端点添加到android项目中。

将您的gcm api密钥(可在开发人员控制台的凭据页面上查看)输入云端点后端的webapp-WEB_INF/appengine-web.xml文件中:

<property name="gcm.api.key" value="your-api-key-here"/>

这样,在Android客户端和MessagingEndpoint内部代码将自动获取api密钥(例如,在端点中它将是行Sender sender = new Sender(API_KEY);,它将为您检索它)。

运行示例gcm android项目,它应该工作。使用您部署的API浏览器发送推送通知。

BIG注意:当您准备在自己的应用程序中使用示例代码时,请确保RegistrationIntentService位于程序包的根目录中,否则它将无法运行!花了一段时间来弄明白......不确定它是不是一个bug或什么。