示例#1
0
  @Override
  protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    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.
        String time = intent.getStringExtra("time");
        sendNotification("Received: " + extras.toString());
      }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
  }
  @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.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)) {
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
        // If it's a regular GCM message, do some work.
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
        System.out.println(extras.toString());
        // Game Logic
        // if we are on the correct page with correct opponent, update UI
        Intent responseIntent = new Intent("com.jajmu.GOT_PUSH");
        responseIntent.putExtras(extras);
        sendOrderedBroadcast(responseIntent, null);
        // otherwise send notification
        //                sendNotification(extras);
        //    			int duration = Toast.LENGTH_SHORT;
        //				Toast toast = Toast.makeText(getApplicationContext(), extras.toString(), duration);
        //				toast.show();
      }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
  }
  @Override
  protected String doInBackground(String... params) {

    String msg = "";
    nick_name = params[0];
    avatar = params[1];
    try {
      if (gcm == null) {
        gcm = GoogleCloudMessaging.getInstance(context);
      }
      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.
      sendRegistrationIdToBackend();

    } catch (IOException ex) {
      ex.printStackTrace();
      msg = "Error: " + ex.getMessage();
    }
    return msg;
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
      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());
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

        for (int i = 0; i < 3; i++) {
          Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
          try {
            Thread.sleep(5000);
          } catch (InterruptedException e) {
          }
        }
        Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

        sendNotification(
            "Message Received from Google GCM Server: " + extras.get(Config.MESSAGE_KEY));
        Log.i(TAG, "Received: " + extras.toString());
      }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
  }
示例#5
0
  @Override
  protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    Bundle extras = intent.getExtras();
    String msg = intent.getStringExtra("message");
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {

      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(500);
          } catch (InterruptedException e) {
          }
        }
        Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
        // Post notification of received message.
        // sendNotification("Received: " + extras.toString());
        sendNotification(msg);
        Log.i(TAG, "Received: " + extras.toString());
      }
    }
    GcmBroadcastReciever.completeWakefulIntent(intent);
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    try {
      Bundle extras = intent.getExtras();
      GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
      sf = getSharedPreferences(Constants.UserInfoSharedPref, MODE_PRIVATE);
      String messageType = gcm.getMessageType(intent);

      if (!extras.isEmpty()) {
        if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
          Article article =
              new Article(
                  Integer.parseInt(extras.getString("id")),
                  extras.getString("name"),
                  extras.getString("email"),
                  extras.getString("title"),
                  Integer.parseInt(extras.getString("category")),
                  Long.parseLong(extras.getString("timestamp")),
                  extras.getInt("publisher"));
          if (sf.getBoolean(Constants.SignInDone, false)) {
            sendNotification(article);
          }
        }
      }
      GcmBroadcastReceiver.completeWakefulIntent(intent);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
示例#7
0
    @SuppressLint("NewApi")
    protected String doInBackground(String... params) {

      try {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);

        regid = gcm.register(GlobalClaass.sender_id);

      } catch (Exception e) {
        // TODO: handle exception
      }

      if (Social_Email.equalsIgnoreCase("")) {
        Social_Email = Social_id;
      }

      if (Social_Type.equalsIgnoreCase("twitter")) Social_Email = "";
      Log.e("Third", "Third");
      try {

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost(GlobalClaass.Webservice_Url);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        Log.e("ID", Social_id);
        Log.e("Email", Social_Email);
        Log.e("Role", Roll_Type);
        Log.e("Social_Type", Social_Type);

        nameValuePairs.add(new BasicNameValuePair("action", "social_connect"));
        nameValuePairs.add(new BasicNameValuePair("social_id", Social_id));
        nameValuePairs.add(new BasicNameValuePair("email", Social_Email));
        nameValuePairs.add(new BasicNameValuePair("social_type", Social_Type));
        nameValuePairs.add(new BasicNameValuePair("role", Roll_Type));
        nameValuePairs.add(new BasicNameValuePair("device", "android"));
        nameValuePairs.add(new BasicNameValuePair("device_id", regid));

        request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpClient.execute(request);

        HttpEntity entity = response.getEntity();

        responseString = EntityUtils.toString(entity);

        Log.e("EResult", "responseString");

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

      return responseString;
    }
  @Override
  protected void onHandleIntent(Intent intent) {
    extras = intent.getExtras();
    String value = extras.getString("message");
    Log.i(TAG, "Bundle 'message' Value = " + value);

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    Log.i(TAG, "in gcm intent Message = " + messageType);
    Log.i(TAG, "in gcm intent Message Bundle = " + extras.toString());

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

        // String received_message=intent.getStringExtra("text_message");

        String received_message = extras.getString("message");
        Log.i(TAG, "received_message = " + received_message);

        if (received_message.equalsIgnoreCase("track")) {
          Log.i(TAG, "In if block, received_message = " + received_message);

          Intent i = new Intent(this, DemoLocation.class);
          i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          i.putExtra("received_message", received_message);
          startActivity(i);
        }

        sendNotification("MESSAGE RECEIVED :" + received_message);

        Intent sendIntent = new Intent("message_recieved");
        sendIntent.putExtra("message", received_message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(sendIntent);
      }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
  }
示例#9
0
    protected String doInBackground(String... params) {

      try {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);

        regid = gcm.register(GlobalClaass.sender_id);

      } catch (Exception e) {
        // TODO: handle exception
      }

      Log.e("DeviceID", regid);
      try {
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        // The default value is zero, that means the timeout is not
        // used.
        int timeoutConnection = 600000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 600000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);

        HttpPost request = new HttpPost(GlobalClaass.Webservice_Url);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

        nameValuePairs.add(new BasicNameValuePair("action", "login"));
        nameValuePairs.add(new BasicNameValuePair("email", emailId));
        nameValuePairs.add(new BasicNameValuePair("password", password));
        nameValuePairs.add(new BasicNameValuePair("device", "android"));
        nameValuePairs.add(new BasicNameValuePair("device_id", regid));

        request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpClient.execute(request);

        HttpEntity entity = response.getEntity();

        responseString = EntityUtils.toString(entity);
        Log.e("Responce", responseString);

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

      return responseString;
    }
  public void init(Context cnt, String tkn, String appid, String ServerUrl)
      throws CommunicatorConnectorException, IOException {
    mContext = cnt.getApplicationContext();
    mUserAuthToken = tkn;

    mAppId = appid;
    mServerUrl = ServerUrl;

    CommunicatorConnector mConnector = null;
    try {
      mConnector = new CommunicatorConnector(mServerUrl, mAppId);

      String regId = "";

      if (!checkPlayServices()) {
        return;
      }

      gcm = GoogleCloudMessaging.getInstance(mContext);

      // Get the existing registration id, if it exists.
      regId = readRegId(mContext); // GCMRegistrar.getRegistrationId(mContext);

      if (regId == null || regId.equals("")) {
        if (mConnector != null) {
          Map<String, Object> mapKey =
              mConnector.requestPublicConfigurationToPush(mAppId, mUserAuthToken);

          // find senderid
          String senderid = String.valueOf(mapKey.get("GCM_SENDER_ID"));
          // register this device for this project
          // senderid= "220741898329";
          regId = gcm.register(senderid);
          if (regId != null && regId.length() > 0) {
            UserSignature signUserSignature = new UserSignature();
            signUserSignature.setAppName(mAppId);
            signUserSignature.setRegistrationId(regId);
            mConnector.registerUserToPush(signUserSignature, mAppId, mUserAuthToken);
            writeRegId(mContext, regId);
          }
        }
      } else {
        // Already registered;
      }

      Log.i("GCM_REGID:", regId);
    } catch (Exception e) {
      gcm.unregister();
      Log.e(TAG, e.toString());
    }
  }
  @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);

    mes = extras.getString("message");
    showNotification();
    Log.i("GCM", "Received : (" + messageType + ")  " + extras.getString("title"));

    GcmBroadcastReceiver.completeWakefulIntent(intent);
  }
示例#12
0
  @Override
  protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    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());
        notifyMe(extras.getString("name"), extras.getString("description"));
      }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
  }
示例#13
0
    @Override
    protected String doInBackground(Void... voids) {
      try {
        final GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(PushActivity.this);
        String registrationId = gcm.register(SENDER_ID);

        LiferayLogger.i("RegistrationId: " + registrationId);

        registerWithLiferayPortal(registrationId);

        return registrationId;
      } catch (IOException ex) {
        LiferayLogger.e("Error", ex);
      }
      return null;
    }
示例#14
0
  /**
   * Registers this application on this device to receive push notifications from Google cloud
   * messaging and registers the resulting device token with Amazon SNS. This creates an Amazon SNS
   * platform endpoint, which can be used to send push notifications directly to this device.
   */
  public void registerDevice() throws IOException {

    // GCM throws a NullPointerException in some failure cases.
    try {
      deviceToken = gcm.register(gcmSenderID);
    } catch (final RuntimeException re) {
      final String error = "Unable to register with GCM. " + re.getMessage();
      Log.e(LOG_TAG, error, re);
      throw new RuntimeException(error, re);
    }

    Log.d(LOG_TAG, "registrationId:" + deviceToken);

    final CreatePlatformEndpointRequest request = new CreatePlatformEndpointRequest();
    request.setPlatformApplicationArn(platformApplicationArn);
    request.setToken(deviceToken);
    final CreatePlatformEndpointResult result = sns.createPlatformEndpoint(request);
    endpointArn = result.getEndpointArn();
    Log.d(LOG_TAG, "endpoint arn: " + endpointArn);

    pushEnabled = true;
    informStateListener();

    sharedPreferences
        .edit()
        .putString(SHARED_PREFS_KEY_DEVICE_TOKEN, deviceToken)
        .putString(SHARED_PREFS_KEY_ENDPOINT_ARN, endpointArn)
        .putBoolean(SHARED_PREFS_PUSH_ENABLED, true)
        .putString(SHARED_PREFS_PREVIOUS_PLATFORM_APPLICATION, platformApplicationArn)
        .commit();
  }
    @Override
    protected String doInBackground(String... params) {
      // RestApi restApi = new RestApi();

      String msg = "";

      try {
        if (gcm == null) {
          gcm = GoogleCloudMessaging.getInstance(context);
        }

        // Nos registramos en los servidores de GCM
        regid = gcm.register(SENDER_ID);

        Log.d(TAG, "Registrado en GCM: registration_id=" + regid);

        // Nos registramos en nuestro servidor
        // boolean registrado = registroServidor(params[0], regid);
        // JSONObject jsonObject = restApi.CreateNewAccount(params[0], regid + "");
        // Log.d(TAG, "" + jsonObject.toString());

        // Guardamos los datos del registro
        // if (jsonObject != null) {
        //     setRegistrationId(context, params[0], regid);
        // }
      } catch (IOException ex) {
        Log.d(TAG, "Error registro en GCM:" + ex.getMessage());
      } catch (Exception e) {
        e.printStackTrace();
      }

      return msg;
    }
      @Override
      protected Integer doInBackground(Void... params) {
        try {
          Context context = getActivity();
          SignalServiceAccountManager accountManager = AccountManagerFactory.createManager(context);
          RedPhoneAccountManager redPhoneAccountManager =
              new RedPhoneAccountManager(
                  BuildConfig.REDPHONE_MASTER_URL,
                  new RedPhoneTrustStore(context),
                  TextSecurePreferences.getLocalNumber(context),
                  TextSecurePreferences.getPushServerPassword(context));

          try {
            accountManager.setGcmId(Optional.<String>absent());
          } catch (AuthorizationFailedException e) {
            Log.w(TAG, e);
          }

          try {
            redPhoneAccountManager.setGcmId(Optional.<String>absent());
          } catch (UnauthorizedException e) {
            Log.w(TAG, e);
          }

          GoogleCloudMessaging.getInstance(context).unregister();

          return SUCCESS;
        } catch (IOException ioe) {
          Log.w(TAG, ioe);
          return NETWORK_ERROR;
        }
      }
 public void onDestroy() {
   super.onDestroy();
   if (mGcmRegistrationListener != null) {
     mAppController.removeListener(mGcmRegistrationListener);
   }
   mGcm.close();
 }
示例#18
0
 public void updateDetails() {
   SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
   String yes = mContext.getString(R.string.gcm_yes);
   String no = mContext.getString(R.string.gcm_no);
   Boolean pref_year7 = preferences.getBoolean("pref_year7", false);
   Boolean pref_year8 = preferences.getBoolean("pref_year8", false);
   Boolean pref_year9 = preferences.getBoolean("pref_year9", false);
   Boolean pref_year10 = preferences.getBoolean("pref_year10", false);
   Boolean pref_year11 = preferences.getBoolean("pref_year11", false);
   Boolean pref_year12 = preferences.getBoolean("pref_year12", false);
   Boolean pref_year13 = preferences.getBoolean("pref_year13", false);
   email = preferences.getString("email", null);
   if (pref_year7) year7 = yes;
   else year7 = no;
   if (pref_year8) year8 = yes;
   else year8 = no;
   if (pref_year9) year9 = yes;
   else year9 = no;
   if (pref_year10) year10 = yes;
   else year10 = no;
   if (pref_year11) year11 = yes;
   else year11 = no;
   if (pref_year12) year12 = yes;
   else year12 = no;
   if (pref_year13) year13 = yes;
   else year13 = no;
   if (gcm == null) gcm = GoogleCloudMessaging.getInstance(mContext);
   if (!getRegistrationId().isEmpty()) update();
 }
 protected transient Void doInBackground(Void avoid[]) {
   if (mGcm == null) {
     mGcm = GoogleCloudMessaging.getInstance(getContext());
   }
   try {
     SLog.dWithTag(
         "GCMRegService",
         (new StringBuilder())
             .append("Registering with senderId=")
             .append(mSenderId)
             .toString());
     avoid = mGcm.register(new String[] {mSenderId});
     SLog.d("GCM: Registration complete with regId={}", avoid);
     setRegistrationId(avoid);
     mAppController.sendGcmRegId(avoid, mUserId);
   }
   // Misplaced declaration of an exception variable
   catch (Void avoid[]) {
     SLog.dWithTag("GCMRegService", "Failed to register with GCM service.");
   }
   // Misplaced declaration of an exception variable
   catch (Void avoid[]) {
   }
   return null;
 }
  @Override
  protected void onHandleIntent(Intent intent) {
    if (intent != null) {
      String senderEmail = getSenderEmail(intent.getStringExtra(MessagingFragment.SENDER_ID_ARG));
      Bundle data = intent.getBundleExtra(MessagingFragment.MESSAGE_ARG);
      String id = Integer.toString(sMessageId.incrementAndGet());
      Log.d(TAG, "Sending gcm message:" + senderEmail + ":" + data + ":" + id);

      try {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        gcm.send(senderEmail, id, data);
        Log.d(TAG, "Sent!");
      } catch (IOException e) {
        Log.e(TAG, "Failed to send GCM Message.", e);
      }
    }
  }
示例#21
0
  // get RegId
  @Override
  protected String doInBackground(Void... params) {
    Log.i("GCM", "starting");

    try {
      if (gcm == null) {
        gcm = GoogleCloudMessaging.getInstance((context));
      }
      regid = gcm.register(PROJECT_NUMBER);
      // msg = "Device registered, registration ID=" + regid;
      Log.i("GCM", regid);

    } catch (IOException ex) {
      Log.i("GCM", "Error :" + ex.getMessage());
    }
    return regid;
  }
    @Override
    protected String doInBackground(String... arg0) {
      String msg = "";
      try {
        if (gcm == null) {
          gcm = GoogleCloudMessaging.getInstance(context);
        }
        regID = gcm.register(SENDER_ID);
        msg = "Dvice registered, registration ID=" + regID;
        Log.d("111", msg);
        sendRegistrationIdToBackend(regID);

        storeRegistrationId(context, regID);
      } catch (IOException ex) {
        msg = "Error :" + ex.getMessage();
      }
      return msg;
    }
 /**
  * @param context
  * @param googleProjectNo
  * @param callBack
  */
 @SuppressLint("NewApi")
 public static void getRegistrationId(
     Context context, String googleProjectNo, App42GCMListener callBack) {
   GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
   String regid = App42GCMController.getRegistrationId(context);
   if (regid.isEmpty()) {
     registeronGCM(context, googleProjectNo, gcm, callBack);
   } else callBack.onGCMRegistrationId(regid);
 }
 protected transient Void doInBackground(Void avoid[]) {
   if (mGcm == null) {
     mGcm = GoogleCloudMessaging.getInstance(getContext());
   }
   SLog.dWithTag("GCMRegService", "Unregistering...");
   mAppController.clearGcmRegId(mRegId, mUserId, mSessionKey);
   GCMRegistrationService.getGCMPreferences(getContext()).edit().clear().commit();
   return null;
 }
  @Override
  protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
      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());
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
        sendNotification("Message Received from Google GCM Server:\n\n" + extras.get("message"));
      }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
  }
  @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("http://10.0.2.2:8080/_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;
  }
示例#27
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //        getSupportActionBar().setDisplayShowHomeEnabled(true);
    //        getSupportActionBar().setIcon(R.mipmap.ic_launcher);

    if (findViewById(R.id.weather_detail_container) != null) {
      // The detail container view will be present only in the large-screen layouts
      // (res/layout-sw600dp). If this view is present, then the activity should be
      // in two-pane mode.
      mTwoPane = true;
      // In two-pane mode, show the detail view in this activity by
      // adding or replacing the detail fragment using a
      // fragment transaction.
      if (savedInstanceState == null) {
        getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.weather_detail_container, new DetailFragment(), DETAILFRAGMENT_TAG)
            .commit();
      }
    } else {
      mTwoPane = false;
      getSupportActionBar().setElevation(0f);
    }

    ForecastFragment forecastFragment =
        ((ForecastFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_forecast));
    forecastFragment.setUseTodayLayout(!mTwoPane);

    SunshineSyncAdapter.initializeSyncAdapter(this);

    // If Google Play Services is not available, some features, such as GCM-powered weather
    // alerts, will not be available.
    if (checkPlayServices()) {
      mGcm = GoogleCloudMessaging.getInstance(this);
      String regId = getRegistrationId(this);

      if (PROJECT_NUMBER.equals("Your Project Number")) {
        new AlertDialog.Builder(this)
            .setTitle("Needs Project Number")
            .setMessage(
                "GCM will not function in Sunshine until you set the Project Number to the one from the Google Developers Console.")
            .setPositiveButton(android.R.string.ok, null)
            .create()
            .show();
      } else if (regId.isEmpty()) {
        registerInBackground(this);
      }
    } else {
      Log.i(LOG_TAG, "No valid Google Play Services APK. Weather alerts will be disabled.");
      // Store regID as null
      storeRegistrationId(this, null);
    }
  }
  @Override
  public void onReceive(Context context, Intent intent) {

    Log.d(TAG, "onHandleIntent - context: " + context);

    // Extract the payload from the message
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
    String messageType = gcm.getMessageType(intent);

    if (extras != null) {
      try {
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
          JSONObject json = new JSONObject();

          json.put("event", "error");
          json.put("message", extras.toString());
          PushPlugin.sendJavascript(json);
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
          JSONObject json = new JSONObject();
          json.put("event", "deleted");
          json.put("message", extras.toString());
          PushPlugin.sendJavascript(json);
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
          // if we are in the foreground, just surface the payload, else post it to the statusbar
          if (PushPlugin.isInForeground()) {
            extras.putBoolean("foreground", true);
            PushPlugin.sendExtras(extras);
          } else {
            extras.putBoolean("foreground", false);

            // Send a notification if there is a message
            if (extras.getString("message") != null && extras.getString("message").length() != 0) {
              createNotification(context, extras);
            }
          }
        }
      } catch (JSONException exception) {
        Log.d(TAG, "JSON Exception was had!");
      }
    }
  }
  @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.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(5000);
          } catch (InterruptedException e) {
          }
        }
        Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
        // Post notification of received message.
        String mensaje = extras.getString("message");
        String enlace = extras.getString("link");
        String titulo = extras.getString("title");
        String imagen = extras.getString("image");
        sendNotification(mensaje, enlace, titulo, imagen);
        Log.i(TAG, "Received: " + extras.toString());
      }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
  }
 public void onCreate() {
   super.onCreate();
   mGcm = GoogleCloudMessaging.getInstance(this);
   mAppController = AppController.getInstance(this);
   mGcmRegistrationListener = new GCMRegistrationListener();
   if (mGcmRegistrationListener != null) {
     mAppController.addListener(mGcmRegistrationListener);
   }
   mSenderId = BuildUtil.getSenderId(this);
   mStartIds = new ArrayList();
 }