/** * Register the device to Google Cloud Messaging service or return registration id if it's already * registered. * * @return registration id or empty string if it's not registered. */ private static String gcmRegisterIfNot(Context context) { String regId = ""; try { GCMRegistrar.checkDevice(context); GCMRegistrar.checkManifest(context); regId = GCMRegistrar.getRegistrationId(context); String gcmId = BuildConfig.GCM_ID; if (gcmId != null && TextUtils.isEmpty(regId)) { GCMRegistrar.register(context, gcmId); } } catch (UnsupportedOperationException e) { // GCMRegistrar.checkDevice throws an UnsupportedOperationException if the device // doesn't support GCM (ie. non-google Android) AppLog.e(T.NOTIFS, "Device doesn't support GCM: " + e.getMessage()); } catch (IllegalStateException e) { // GCMRegistrar.checkManifest or GCMRegistrar.register throws an IllegalStateException if // Manifest // configuration is incorrect (missing a permission for instance) or if GCM dependencies are // missing AppLog.e( T.NOTIFS, "APK (manifest error or dependency missing) doesn't support GCM: " + e.getMessage()); } catch (Exception e) { // SecurityException can happen on some devices without Google services (these devices // probably strip // the AndroidManifest.xml and remove unsupported permissions). AppLog.e(T.NOTIFS, e); } return regId; }
public void setupPushNotification() { // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(this); // Make sure the manifest was properly set - comment out this line // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(this); // registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); // Get GCM registration id String regId = GCMRegistrar.getRegistrationId(this); // Check if regid already presents if (regId.equals("")) { // Registration is not present, register now with GCM GCMRegistrar.register(this, ApplicationConstants.SENDER_ID); } else { // Device is already registered on GCM if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration. Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG) .show(); } } }
public static void removeWpComUserRelatedData(Context context) { // cancel all Volley requests - do this before unregistering push since that uses // a Volley request VolleyUtils.cancelAllRequests(requestQueue); NotificationsUtils.unregisterDevicePushNotifications(context); try { GCMRegistrar.checkDevice(context); GCMRegistrar.unregister(context); } catch (Exception e) { AppLog.v(T.NOTIFS, "Could not unregister for GCM: " + e.getMessage()); } // delete wpcom blogs wpDB.deleteWordPressComBlogs(context); // reset default account AccountHelper.getDefaultAccount().signout(); // reset all reader-related prefs & data AppPrefs.reset(); ReaderDatabase.reset(); // Reset Stats Data StatsDatabaseHelper.getDatabase(context).reset(); // Reset Simperium buckets (removes local data) SimperiumUtils.resetBucketsAndDeauthorize(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tabs); preferenciasFragment = new PreferenciasFragment(); preferenciasFragment.setPreferencesListener(this); inicioFragment = new InicioFragment(); inicioFragment.setInicioLoadedListener(this); crearMapFragment(); ArrayList<Fragment> fragments = new ArrayList<Fragment>(); fragments.add(preferenciasFragment); fragments.add(inicioFragment); if (myMapFragment != null) { fragments.add(myMapFragment); } mSectionsPagerAdapter = new SectionsPagerAdapter(this, getFragmentManager(), fragments); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // mViewPager.setCurrentItem(1); mViewPager.setOnPageChangeListener(this); registroGCM(); GCMRegistrar.checkDevice(this); GCMRegistrar.register(this, "834884443249"); servicioGuardarPosicion(); }
/** * register to the server * * @param context Activity or Service context * @param regId gcmId registered from Google */ public static boolean register(Context context, String regId) { String serverUrl = ServerUrl.SERVER_URL_GCM_REGISTER(); String uid = PreferenceControl.getUID(); try { DefaultHttpClient httpClient = HttpSecureClientGenerator.getSecureHttpClient(); HttpPost httpPost = new HttpPost(serverUrl); httpClient .getParams() .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("uid", uid); builder.addTextBody("regId", regId); httpPost.setEntity(builder.build()); boolean result = uploader(httpClient, httpPost); GCMRegistrar.setRegisteredOnServer(context, result); return result; } catch (Exception e) { GCMRegistrar.setRegisteredOnServer(context, false); return false; } }
private void registerForPush() { GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); REG_ID = GCMRegistrar.getRegistrationId(this); if (REG_ID.equals("")) { GCMRegistrar.register(this, "336168193323"); } else { System.out.println("Already Registered"); } }
public static boolean register( final Context context, final String regId, /* optional */ final String oldId) { Log.i(TAG, "registering device"); String serverUrl = Secret.SERVER_REG_URL; Map<String, String> params = new HashMap<String, String>(); params.put(P_REGID, regId); params.put(P_USER, PrefsHelper.getUser(context)); params.put(P_PWD, PrefsHelper.getPwd(context)); if (oldId != "") { params.put(P_OLDID, oldId); } long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // app server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { if (GCMRegistrar.isRegisteredOnServer(context)) { // AsyncTask finished meanwhile, return return false; } Log.d(TAG, "Attempt #" + i + " to register"); try { String message = post(serverUrl, params); if (message.contains("Successfully added") || message.contains("already registered")) { GCMRegistrar.setRegisteredOnServer(context, true); GCMHelper.displayMessage(context, message); return true; } else { // dont backoff in case of a wrong password GCMHelper.displayMessage(context, message); return false; } } catch (IOException e) { Log.e(TAG, "Failed to register on attempt " + i, e); if (i == MAX_ATTEMPTS) { break; } try { Log.d(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Log.d(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return false; } // increase backoff exponentially backoff *= 2; } } String message = context.getString(R.string.server_register_error, MAX_ATTEMPTS); GCMHelper.displayMessage(context, message); return false; }
@Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) { boolean result = false; Log.v(TAG, "execute: action=" + action); if (REGISTER.equals(action)) { Log.v(TAG, "execute: data=" + data.toString()); try { JSONObject jo = data.getJSONObject(0); gWebView = this.webView; Log.v(TAG, "execute: jo=" + jo.toString()); gECB = (String) jo.get("ecb"); gSenderID = (String) jo.get("senderID"); Log.v(TAG, "execute: ECB=" + gECB + " senderID=" + gSenderID); GCMRegistrar.register(getApplicationContext(), gSenderID); result = true; callbackContext.success(); } catch (JSONException e) { Log.e(TAG, "execute: Got JSON Exception " + e.getMessage()); result = false; callbackContext.error(e.getMessage()); } if (gCachedExtras != null) { Log.v(TAG, "sending cached extras"); sendExtras(gCachedExtras); gCachedExtras = null; } } else if (UNREGISTER.equals(action)) { GCMRegistrar.unregister(getApplicationContext()); Log.v(TAG, "UNREGISTER"); result = true; callbackContext.success(); } else { result = false; Log.e(TAG, "Invalid action : " + action); callbackContext.error("Invalid action : " + action); } return result; }
private void initGCM() { try { // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(this); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { // Automatically registers application on startup. GCMRegistrar.register(this, SENDER_ID); } } catch (Exception e) { EasyTracker.getTracker().trackException("cannot init GCM", e, false); } }
@Override public void run() { final Context context = SuperManActivity_No_Pusher.this; CommonUtilities.UUID = UUID; // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(context); // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(context); registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); final String regId = GCMRegistrar.getRegistrationId(context); Log.e(TAG, "regId: " + regId); if (regId.equals("")) { // Automatically registers application on startup. mRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { GCMRegistrar.register(context, SENDER_ID); return null; } @Override protected void onPostExecute(Void result) { mRegisterTask = null; } }; mRegisterTask.execute(null, null, null); } else { // Device is already registered on GCM, check server. if (GCMRegistrar.isRegisteredOnServer(context)) { mRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { ServerUtilities.register(context, regId); return null; } @Override protected void onPostExecute(Void result) { mRegisterTask = null; } }; mRegisterTask.execute(null, null, null); } } }
public static void appLogout( boolean isUserUpdateConflict, boolean isServerError, boolean isInvalidToken) { Activity fromActivity = SideBarActivity.getValidContext(); Intent goToSignIn = new Intent(fromActivity, SignInActivity.class); if (isServerError) { goToSignIn.putExtra("password_from_prefs", SpikaApp.getPreferences().getUserPassword()); goToSignIn.putExtra("email_from_prefs", SpikaApp.getPreferences().getUserEmail()); } if (isInvalidToken) { goToSignIn.putExtra("invalid_token", true); } GCMRegistrar.unregister(SpikaApp.getInstance().getApplicationContext()); SpikaApp.getPreferences().setWatchingGroupId(""); SpikaApp.getPreferences().setWatchingGroupRev(""); if (SideBarActivity.sInstance != null) { goToSignIn.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); SideBarActivity.sInstance.startActivity(goToSignIn); sendBroadcastLogout(SideBarActivity.sInstance); } else if (SplashScreenActivity.sInstance != null) { SplashScreenActivity.sInstance.startActivity(goToSignIn); sendBroadcastLogout(SplashScreenActivity.sInstance); } }
public static void getTagsAsync(final Context context, final GetTagsListener listener) { if (GCMRegistrar.isRegisteredOnServer(context) == false) return; Handler handler = new Handler(context.getMainLooper()); handler.post( new Runnable() { public void run() { AsyncTask<Void, Void, Void> task = new WorkerTask(context) { @Override protected void doWork(Context context) { Map<String, Object> tags; try { tags = DeviceFeature2_5.getTags(context); listener.onTagsReceived(tags); } catch (Exception e) { listener.onError(e); } } }; ExecutorHelper.executeAsyncTask(task); } }); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test_activity); gcmRegId = GCMRegistrar.getRegistrationId(this); jpushRegId = JPushInterface.getRegistrationID(this); tv = (TextView) findViewById(R.id.test_tv); tv.setText( "GCMregId:" + gcmRegId + LINE + "jpushRegId:" + jpushRegId + LINE + "string.xml server:" + getString(R.string.server_address) + LINE + "Server IP:" + Constants.hostUrl + LINE + "ETS Server:" + Constants.ETShostUrl); }
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Register application for Google Cloud Messaging GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); // Remove in production final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { GCMRegistrar.register(this, Utils.SENDER_ID); } else { Log.v(TAG, "Already registered"); } setContentView(R.layout.messages); }
private void registerDevice() { if (mSenderID == null) { throw new IllegalArgumentException( "sender ID is required in order to register this device for push notifications. You must specify the senderId in the ApplicationManifest or when calling the JavaScript API."); } GCMRegistrar.register(mContext, mSenderID); }
/** @param context current context */ public void onStartup(Context context, boolean registerAppOpen) { // check for manifest and permissions pushRegistrar.checkDevice(context); if (registerAppOpen) sendAppOpen(context); final String regId = GCMRegistrar.getRegistrationId(context); if (regId.equals("")) { // Automatically registers application on startup. pushRegistrar.registerPW(context); } else { if (context instanceof Activity) { if (((Activity) context).getIntent().hasExtra(PushManager.PUSH_RECEIVE_EVENT)) { // if this method calls because of push message, we don't need to register return; } } // if we need to re-register on Pushwoosh because of Pushwoosh App Id change if (forceRegister) { registerOnPushWoosh(context, regId); } else { if (neededToRequestPushWooshServer(context)) { registerOnPushWoosh(context, regId); } else { PushEventsTransmitter.onRegistered(context, regId); } } } }
public void onDestroy() { GCMRegistrar.onDestroy(getApplicationContext()); gWebView = null; gECB = null; gForeground = false; super.onDestroy(); }
protected void registerGCM() { try { String senderId = app.getAppJsonSetting().getSenderId(); // GCM registration process GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { GCMRegistrar.register(this, senderId); } else { ((MonacaApplication) getApplication()).sendGCMRegisterIdToAppAPI(regId); } } catch (Exception e) { MyLog.d(TAG, "this device or application does not support GCM"); e.printStackTrace(); } }
@Override protected void onDestroy() { if (mRegisterTask != null) { mRegisterTask.cancel(true); } unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(this); super.onDestroy(); }
// GCM @Override protected void onDestroy() { // TODO Auto-generated method stub if (mRegisterTask != null) { mRegisterTask.cancel(true); } unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(getApplicationContext()); super.onDestroy(); }
/** * Check if user has valid credentials, and that at least 2 minutes are passed since the last * ping, then try to update the PN token. */ private void updatePushNotificationTokenIfNotLimited() { // Synch Push Notifications settings if (isPushNotificationPingNeeded() && AccountHelper.isSignedInWordPressDotCom()) { String token = null; try { // Register for Google Cloud Messaging GCMRegistrar.checkDevice(mContext); GCMRegistrar.checkManifest(mContext); token = GCMRegistrar.getRegistrationId(mContext); String gcmId = BuildConfig.GCM_ID; if (gcmId == null || token == null || token.equals("")) { AppLog.e(T.NOTIFS, "Could not ping the PNs backend, Token or gmcID not found"); } else { // Send the token to WP.com NotificationsUtils.registerDeviceForPushNotifications(mContext, token); } } catch (Exception e) { AppLog.e(T.NOTIFS, "Could not ping the PNs backend: " + e.getMessage()); } } }
/** Unregister this account/device pair within the server. */ static void unregister(final Context context, final String regId) { String serverUrl = SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); String message = context.getString(R.string.server_unregistered); CommonUtilities.displayMessage(context, message); } catch (IOException e) { } }
@Override protected void onUnregistered(Context context, String registrationId) { // Log.i(TAG, "Device unregistered"); CommonUtilities.displayMessage(context, "Device Unregistered"); if (GCMRegistrar.isRegisteredOnServer(context)) { } else { // This callback results from the call to unregister made on // ServerUtilities when the registration to the server failed. // Log.i(TAG, "Ignoring unregister callback"); } }
public void onDestroy() { try { if (mRegisterTask != null) { mRegisterTask.cancel(true); } unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(this); } catch (Exception e) { e.printStackTrace(); } super.onDestroy(); }
@Override protected void onDestroy() { if (mRegisterTask != null) { mRegisterTask.cancel(true); } try { unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(this); } catch (Exception e) { Log.e("UnRegister Receiver Error", "> " + e.getMessage()); } super.onDestroy(); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); setContentView(R.layout.main); tv_sender_nickname = (TextView) findViewById(R.id.sender_nickname); tv_recipients_nickname = (TextView) findViewById(R.id.recipients_nickname); tv_message = (TextView) findViewById(R.id.message); btn_read_more_button = (Button) findViewById(R.id.read_more_button); final String regId = GCMRegistrar.getRegistrationId(this); Log.i(debugAppTag, "registration id == " + regId); if (regId.equals("")) { GCMRegistrar.register(this, ApplicationContext.getSenderID()); } else { Log.v(debugAppTag, "Already registered"); } }
private PluginResult internalUnregister(JSONArray data, String callbackId) { callbackIds.put("unregisterDevice", callbackId); PluginResult result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); try { GCMRegistrar.unregister(cordova.getActivity()); } catch (Exception e) { return new PluginResult(Status.ERROR); } return result; }
private boolean internalUnregister(JSONArray data, CallbackContext callbackContext) { callbackIds.put("unregisterDevice", callbackContext); try { GCMRegistrar.unregister(cordova.getActivity()); } catch (Exception e) { callbackIds.remove("unregisterDevice"); callbackContext.error(e.getMessage()); return true; } return true; }
/** * Called after the device has been unregisterd from the GCM server. We we are registered on the * AirBop servers we should unregister from there as well. */ @Override protected void onUnregistered(Context context, String registrationId) { Log.i(TAG, "Device unregistered"); displayMessage(context, getString(R.string.gcm_unregistered)); // If we are still registered with AirBop it is time to unregister if (GCMRegistrar.isRegisteredOnServer(context)) { AirBopServerUtilities.unregister(context, registrationId); } else { // This callback results from the call to unregister made on // ServerUtilities when the registration to the server failed. Log.i(TAG, "Ignoring unregister callback"); } }
@Override public void parseResponseFromServer(String result) { if (statusCode == HttpStatus.SC_OK) { GCMRegistrar.setRegisteredOnServer(context, true); } else { // Display error messages // Expected {error: String} JSON JSONObject obj; try { obj = new JSONObject(result); Util.alertToast(context, obj.getString("error")); } catch (JSONException e) { Log.e("Util", "JSON Parsing Error"); } } }