0

去年,當您向Android Studio項目添加Cloud Endpoints plus GCM模塊時,IDE在backendapp中創建了一些示例代碼,展示瞭如何將GCM與雲端點一起使用。未棄用的GCM雲端點示例2016

但是,使用較新版本的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,我想知道如果任何人有任何當前工作的非過時的例子也許你可以建議一些編輯上面的代碼如果你知道你在做什麼......?非常感謝!

+0

您可以閱讀本文檔(https://developers.google.com/cloud-messaging/c2dm#history)瞭解如何從C2DM遷移到GCM。在C2DM中,發件人ID是電子郵件地址。在GCM中,發件人ID是您從API控制檯獲取的項目編號。檢查這個[示例](https://github.com/google/gcm)可能有幫助。 – abielita

回答

0

想要在這裏給人們一個小指南,以防他們迷路。

首先檢查出來,並隨時獲得最新與此谷歌雲端通訊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位於包裝的根部,否則它將無法工作!花了一段時間來弄清楚......不知道它是一個錯誤還是什麼。