Example usage for android.os Bundle keySet

List of usage examples for android.os Bundle keySet

Introduction

In this page you can find the example usage for android.os Bundle keySet.

Prototype

public Set<String> keySet() 

Source Link

Document

Returns a Set containing the Strings used as keys in this Bundle.

Usage

From source file:com.google.android.gcm.demo.logic.DeviceGroupsHelper.java

/**
 * Execute the HTTP call to remove registration_ids from a the Device Group.
 *
 * <code>//from   w  w w.  java  2  s.  c o m
 *   Content-Type: application/json
 *   Authorization: key=API_KEY
 *   project_id: SENDER_ID
 *   {
 *     "operation": "add",
 *     "notification_key_name": "appUser-Chris",
 *     "notification_key": "aUniqueKey",
 *     "registration_ids": ["4", "8", "15", "16", "23", "42"]
 *   }
 * </code>
 */
public void addMembers(String senderId, String apiKey, String groupName, String groupKey, Bundle members) {
    try {
        HttpRequest httpRequest = new HttpRequest();
        httpRequest.setHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);
        httpRequest.setHeader(HEADER_AUTHORIZATION, "key=" + apiKey);
        httpRequest.setHeader(HEADER_PROJECT_ID, senderId);

        JSONObject requestBody = new JSONObject();
        requestBody.put("operation", "add");
        requestBody.put("notification_key_name", groupName);
        requestBody.put("notification_key", groupKey);
        requestBody.put("registration_ids", new JSONArray(bundleValues2Array(members)));

        httpRequest.doPost(GCM_GROUPS_ENDPOINT, requestBody.toString());

        JSONObject responseBody = new JSONObject(httpRequest.getResponseBody());

        if (responseBody.has("error")) {
            mLogger.log(Log.INFO, "Error while adding new group members." + "\ngroupName: " + groupName
                    + "\ngroupKey: " + groupKey + "\nhttpResponse: " + httpRequest.getResponseBody());
            MainActivity.showToast(mContext, R.string.group_toast_add_members_failed,
                    responseBody.getString("error"));
        } else {
            // Store the group in the local storage.
            Sender sender = mSenders.getSender(senderId);
            DeviceGroup newGroup = sender.groups.get(groupName);
            for (String name : members.keySet()) {
                newGroup.tokens.put(name, members.getString(name));
            }
            mSenders.updateSender(sender);

            mLogger.log(Log.INFO, "Group members added successfully." + "\ngroupName: " + groupName
                    + "\ngroupKey: " + groupKey);
            MainActivity.showToast(mContext, R.string.group_toast_add_members_succeeded);
        }
    } catch (JSONException | IOException e) {
        mLogger.log(Log.INFO, "Exception while adding new group members." + "\nerror: " + e.getMessage()
                + "\ngroupName: " + groupName + "\ngroupKey: " + groupKey);
        MainActivity.showToast(mContext, R.string.group_toast_add_members_failed, e.getMessage());
    }
}

From source file:com.supremainc.biostar2.push.GcmBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "========push receiver start =========");
    }//from www.j  ava2 s. co  m

    Bundle bundle = intent.getExtras();
    if (bundle == null) {
        setResultCode(Activity.RESULT_OK);
        return;
    }

    if (REGISTER_RESPONSE_ACTION.equals(intent.getAction())) {
        String registrationId = intent.getStringExtra("registration_id");
        Log.e(TAG, "registered:" + registrationId);
        if ((registrationId != null) && (registrationId.length() > 0)) {
            PreferenceUtil.putSharedPreference(context, "registrationId", registrationId);
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            PreferenceUtil.putSharedPreference(context, "version", packageInfo.versionCode);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        PushDataProvider pushDataProvider = PushDataProvider.getInstance(context);
        pushDataProvider.setNeedUpdateNotificationToken(registrationId);
        ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
        startWakefulService(context, intent.setComponent(comp));
        setResultCode(Activity.RESULT_OK);
        if (BuildConfig.DEBUG) {
            Log.i(TAG, "========push receiver end =========");
        }
        return;
    }
    PushNotification noti = null;
    for (String key : bundle.keySet()) {
        String value;
        try {
            value = (String) bundle.get(key);
        } catch (Exception e) {
            Log.e(TAG, " " + e.getMessage());
            continue;
        }
        if (value == null) {
            continue;
        }
        if (key.equals("CMD") && value.equals("RST_FULL")) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "RST_FULL");
            }
            int registeredVersion = PreferenceUtil.getIntSharedPreference(context, "version");
            if (registeredVersion > 0) {
                registeredVersion--;
            }
            PreferenceUtil.putSharedPreference(context, "version", registeredVersion);
            Intent intentBoradCast = new Intent(Setting.BROADCAST_PUSH_TOKEN_UPDATE);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intentBoradCast);
            return;
        }
        String code = null;
        if (key.equals(NotificationType.DEVICE_REBOOT.mName)) {
            code = NotificationType.DEVICE_REBOOT.mName;
        } else if (key.equals(NotificationType.DEVICE_RS485_DISCONNECT.mName)) {
            code = NotificationType.DEVICE_RS485_DISCONNECT.mName;
        } else if (key.equals(NotificationType.DEVICE_TAMPERING.mName)) {
            code = NotificationType.DEVICE_TAMPERING.mName;
        } else if (key.equals(NotificationType.DOOR_FORCED_OPEN.mName)) {
            code = NotificationType.DOOR_FORCED_OPEN.mName;
        } else if (key.equals(NotificationType.DOOR_HELD_OPEN.mName)) {
            code = NotificationType.DOOR_HELD_OPEN.mName;
        } else if (key.equals(NotificationType.DOOR_OPEN_REQUEST.mName)) {
            code = NotificationType.DOOR_OPEN_REQUEST.mName;
        } else if (key.equals(NotificationType.ZONE_APB.mName)) {
            code = NotificationType.ZONE_APB.mName;
        } else if (key.equals(NotificationType.ZONE_FIRE.mName)) {
            code = NotificationType.ZONE_FIRE.mName;
        }
        if (code != null) {
            PushNotification tempNoti = NotificationBuild(value, code, context);
            if (tempNoti != null) {
                noti = tempNoti;
            }
        }

        if (BuildConfig.DEBUG) {
            Log.i(TAG, "|" + String.format("%s : %s (%s)", key, value.toString(), value.getClass().getName())
                    + "|");
        }
    }

    if (noti != null) {
        Notification(noti, context);
    }

    ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
    startWakefulService(context, intent.setComponent(comp));
    setResultCode(Activity.RESULT_OK);
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "========push receiver end =========");
    }
}

From source file:com.google.android.gcm.demo.logic.DeviceGroupsHelper.java

/**
 * Execute the HTTP call to remove registration_ids from a the Device Group.
 *
 * <code>/*from  w  ww  .  ja  va  2  s. c  om*/
 *   Content-Type: application/json
 *   Authorization: key=API_KEY
 *   project_id: SENDER_ID
 *   {
 *     "operation": "remove",
 *     "notification_key_name": "appUser-Chris",
 *     "notification_key": "aUniqueKey",
 *     "registration_ids": ["4", "8", "15", "16", "23", "42"]
 *   }
 * </code>
 */
public void removeMembers(String senderId, String apiKey, String groupName, String groupKey, Bundle members) {
    try {
        HttpRequest httpRequest = new HttpRequest();
        httpRequest.setHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);
        httpRequest.setHeader(HEADER_AUTHORIZATION, "key=" + apiKey);
        httpRequest.setHeader(HEADER_PROJECT_ID, senderId);

        JSONObject requestBody = new JSONObject();
        requestBody.put("operation", "remove");
        requestBody.put("notification_key_name", groupName);
        requestBody.put("notification_key", groupKey);
        requestBody.put("registration_ids", new JSONArray(bundleValues2Array(members)));

        httpRequest.doPost(GCM_GROUPS_ENDPOINT, requestBody.toString());

        JSONObject responseBody = new JSONObject(httpRequest.getResponseBody());

        if (responseBody.has("error")) {
            mLogger.log(Log.INFO, "Error while removing group members." + "\ngroupName: " + groupName
                    + "\ngroupKey: " + groupKey + "\nhttpResponse: " + httpRequest.getResponseBody());
            MainActivity.showToast(mContext, R.string.group_toast_remove_members_failed,
                    responseBody.getString("error"));
        } else {
            // Store the group in the local storage.
            SenderCollection senders = SenderCollection.getInstance(mContext);
            Sender sender = senders.getSender(senderId);
            DeviceGroup newGroup = sender.groups.get(groupName);
            for (String name : members.keySet()) {
                newGroup.tokens.remove(name);
            }
            senders.updateSender(sender);

            mLogger.log(Log.INFO, "Group members removed successfully." + "\ngroupName: " + groupName
                    + "\ngroupKey: " + groupKey);
            MainActivity.showToast(mContext, R.string.group_toast_remove_members_succeeded);
        }
    } catch (JSONException | IOException e) {
        mLogger.log(Log.INFO, "Exception while removing group members." + "\nerror: " + e.getMessage()
                + "\ngroupName: " + groupName + "\ngroupKey: " + groupKey);
        MainActivity.showToast(mContext, R.string.group_toast_remove_members_failed, e.getMessage());
    }
}

From source file:com.canappi.connector.yp.yhere.SearchView.java

public void viewDidLoad() {

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        Set<String> keys = extras.keySet();
        for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
            String key = iter.next();
            Class c = SearchView.class;
            try {
                Field f = c.getDeclaredField(key);
                Object extra = extras.get(key);
                String value = extra.toString();
                f.set(this, value);
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from  www.java2  s .  c  om
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {

    }

    searchViewIds = new HashMap();
    searchViewValues = new HashMap();

    isUserDefault = false;

    resultsListView = (ListView) findViewById(R.id.resultsTable);
    resultsAdapter = new ResultsEfficientAdapter(this);

    businessNameArray = new ArrayList<String>();

    latitudeArray = new ArrayList<String>();

    longitudeArray = new ArrayList<String>();

    listingIdArray = new ArrayList<String>();

    phoneArray = new ArrayList<String>();

    callArray = new ArrayList<String>();

    streetArray = new ArrayList<String>();

    cityArray = new ArrayList<String>();
    resultsListView.setAdapter(resultsAdapter);
    didSelectViewController();

}

From source file:com.wareninja.android.opensource.mongolab_sdk.common.WebService.java

public String webPost(String methodName, Bundle params) throws MalformedURLException, IOException {

    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";
    OutputStream os;//from   ww  w .  j  a  va2  s.com

    ret = null;

    String postUrl = webServiceUrl + methodName;

    if (AppContext.isDebugMode())
        Log.d(TAG, "POST URL: " + postUrl);
    HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection();

    /*for (RequestHeader header : headers) {
       if (header != null) {
    conn.setRequestProperty(header.getKey(), header.getValue());
            
    if (AppContext.isDebugMode()) {
       Log.d(TAG, String.format("httpDelete.setHeader(%s, %s)", header.getKey(), header.getValue()) );
    }
       }
    }*/

    //if ( TextUtils.isEmpty(conn.getRequestProperty("User-Agent")) ) {
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " WareNinjaAndroidSDK"//"com.wareninja.android.mayormonster"//CommonUtils.getMyUserAgent(mContext)//
    );
    //}

    Bundle dataparams = new Bundle();
    for (String key : params.keySet()) {

        byte[] byteArr = null;
        try {
            byteArr = (byte[]) params.get(key);
        } catch (Exception ex1) {
        }
        if (byteArr != null)
            dataparams.putByteArray(key, byteArr);
    }

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Connection", "Keep-Alive");
    appendRequestHeaders(conn, headers);
    conn.connect();
    os = new BufferedOutputStream(conn.getOutputStream());

    os.write(("--" + strBoundary + endLine).getBytes());
    os.write((CommonUtils.encodePostBody(params, strBoundary)).getBytes());
    os.write((endLine + "--" + strBoundary + endLine).getBytes());

    if (!dataparams.isEmpty()) {

        for (String key : dataparams.keySet()) {
            os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
            os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
            os.write(dataparams.getByteArray(key));
            os.write((endLine + "--" + strBoundary + endLine).getBytes());

        }
    }
    os.flush();

    String response = "";
    try {
        response = CommonUtils.read(conn.getInputStream());
        //mHttpResponseCode = conn.getResponseCode();
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = CommonUtils.read(conn.getErrorStream());
    }
    if (AppContext.isDebugMode())
        Log.d(TAG, "POST response: " + response);

    return response;
}

From source file:jackpal.androidterm.Term.java

private String makePathFromBundle(Bundle extras) {
    if (extras == null || extras.size() == 0) {
        return "";
    }// w ww . j av  a  2  s .  c  o m

    String[] keys = new String[extras.size()];
    keys = extras.keySet().toArray(keys);
    Collator collator = Collator.getInstance(Locale.US);
    Arrays.sort(keys, collator);

    StringBuilder path = new StringBuilder();
    for (String key : keys) {
        String dir = extras.getString(key);
        if (dir != null && !dir.equals("")) {
            path.append(dir);
            path.append(":");
        }
    }

    return path.substring(0, path.length() - 1);
}

From source file:com.google.android.gcm.demo.logic.DeviceGroupsHelper.java

/**
 * Execute the HTTP call to create the Device Group in background.
 *
 * <code>/*from ww w.  ja  v a2  s.co  m*/
 *   Content-Type: application/json
 *   Authorization: key=API_KEY
 *   project_id: SENDER_ID
 *   {
 *     "operation": "create",
 *     "notification_key_name": "appUser-Chris",
 *     "registration_ids": ["4", "8", "15", "16", "23", "42"]
 *   }
 * </code>
 */
public void asyncCreateGroup(final String senderId, final String apiKey, final String groupName,
        Bundle members) {
    final Bundle newMembers = new Bundle(members);
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                HttpRequest httpRequest = new HttpRequest();
                httpRequest.setHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);
                httpRequest.setHeader(HEADER_AUTHORIZATION, "key=" + apiKey);
                httpRequest.setHeader(HEADER_PROJECT_ID, senderId);

                JSONObject requestBody = new JSONObject();
                requestBody.put("operation", "create");
                requestBody.put("notification_key_name", groupName);
                requestBody.put("registration_ids", new JSONArray(bundleValues2Array(newMembers)));

                httpRequest.doPost(GCM_GROUPS_ENDPOINT, requestBody.toString());

                JSONObject responseBody = new JSONObject(httpRequest.getResponseBody());

                if (responseBody.has("error")) {
                    mLogger.log(Log.INFO, "Group creation failed." + "\ngroupName: " + groupName
                            + "\nhttpResponse:" + httpRequest.getResponseBody());
                    MainActivity.showToast(mContext, R.string.group_toast_group_creation_failed,
                            responseBody.getString("error"));
                } else {
                    // Store the group in the local storage.
                    DeviceGroup group = new DeviceGroup();
                    group.notificationKeyName = groupName;
                    group.notificationKey = responseBody.getString("notification_key");
                    for (String name : newMembers.keySet()) {
                        group.tokens.put(name, newMembers.getString(name));
                    }

                    Sender sender = mSenders.getSender(senderId);
                    sender.groups.put(group.notificationKeyName, group);
                    mSenders.updateSender(sender);

                    mLogger.log(Log.INFO, "Group creation succeeded." + "\ngroupName: "
                            + group.notificationKeyName + "\ngroupKey: " + group.notificationKey);
                    MainActivity.showToast(mContext, R.string.group_toast_group_creation_succeeded);
                }
            } catch (JSONException | IOException e) {
                mLogger.log(Log.INFO, "Exception while creating a new group" + "\nerror: " + e.getMessage()
                        + "\ngroupName: " + groupName);
                MainActivity.showToast(mContext, R.string.group_toast_group_creation_failed, e.getMessage());
            }
            return null;
        }
    }.execute();
}

From source file:org.restcomm.app.qoslib.Utils.RTWebSocket.java

public int sendIntentToWebSocket(String action, Bundle intentExtras) {
    if (mWebSocketClient != null && wsConnected) {
        if (action.equals(CommonIntentBundleKeysOld.ACTION_CONNECTION_UPDATE) || intentExtras == null)
            return 0; // writing intents about data connections can cause a vicious cycle, as writing them causes new intents which will be written
        if (action.equals("android.intent.action.ANY_DATA_STATE"))
            return 0; // this is great information, but could potentially contain a password and get us in trouble
        //if (action.equals(CommonIntentBundleKeysOld.ACTION_GPS_STATUS_UPDATE))
        //   return 0;
        //Retrieve api key if it exists
        String apiKey = context.getApiKey(context);
        String actionKey = "";
        int pos = action.lastIndexOf('.');
        actionKey = action.substring(pos + 1);
        String message = null;//  w ww. j  a  v  a 2s  . co  m
        try {
            JSONObject jobj = new JSONObject();

            jobj.put("url", "/api/devices/feed");
            jobj.put("callbackid", "x");
            JSONObject jparams = new JSONObject();
            jparams.put(WebReporter.JSON_API_KEY, apiKey);
            jparams.put("type", "intent");
            jparams.put("intent", actionKey);

            if (action.equals(CommonIntentBundleKeysOld.ACTION_CONNECTION_UPDATE)) {
                //               String connectString = intentExtras.getString(CommonIntentBundleKeysOld.KEY_UPDATE_CONNECTION);
                //               String[] vals = connectString.split(",");
                //               jparams.put("TYPE", vals[0]);
                //               jparams.put("STATE", vals[1]);
                //               jparams.put("ACT", vals[2]);
            } else {
                for (String key : intentExtras.keySet()) {
                    Object value = intentExtras.get(key);
                    jparams.put(key, value);
                    if (key.equals(CommonIntentBundleKeysOld.EXTRA_SENDSOCKET)
                            && intentExtras.getBoolean(key) == false)
                        return 1;
                }
            }
            jobj.put("params", jparams);
            message = jobj.toString();
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.WTF, TAG, "sendIntentToWebSocket", "json exception: ", e);
        }

        if (message != null)
            queueSocketSend(message);

    }
    return 0;
}

From source file:terse.a1.TerseActivity.java

private void viewPath2parseQuery(String queryStr, Bundle extras) {
    // Url query.
    taQuery = new HashMap<String, String>();
    queryStr = queryStr == null ? "" : queryStr; // Don't be null.

    String[] parts = queryStr.split("&");
    for (String part : parts) {
        String[] kv = part.split("=", 2);
        if (kv.length == 2)
            try {
                taQuery.put(kv[0], URLDecoder.decode(kv[1], "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();/* w ww.j a  v  a2  s  .c  o  m*/
                terp.toss("%s", e);
            }
    }
    if (extras != null) {
        for (String key : extras.keySet()) {
            taQuery.put(key, extras.getString(key));
        }
    }
}

From source file:com.acc.android.network.operator.base.BaseHttpOperator.java

private String encodeUrlParam(Object paramObject) throws UnsupportedEncodingException {
    if (paramObject == null)
        return HttpConstant.DEFAULTPARAM;
    StringBuilder sb = new StringBuilder();
    if (paramObject instanceof Bundle) {
        Bundle bundle = (Bundle) paramObject;
        if (bundle.size() == 0) {
            return HttpConstant.DEFAULTPARAM;
        } else {/*from   w  ww .  j ava2  s.c o m*/
            boolean isFirst = true;
            for (String key : bundle.keySet()) {
                if (isFirst)
                    isFirst = false;
                else
                    sb.append("&");
                // Object object;
                sb.append(key + "=" + URLEncoder.encode(bundle.getString(key), HttpConstant.ENCODE));
                // + paramBundle.getString(key));
            }
        }
    } else if (paramObject instanceof Map) {
        HashMap<String, String> map = (HashMap<String, String>) paramObject;
        if (map.size() == 0) {
            return HttpConstant.DEFAULTPARAM;
        } else {
            boolean isFirst = true;
            for (Object key : map.keySet()) {
                if (isFirst)
                    isFirst = false;
                else
                    sb.append("&");
                // Object object;
                sb.append(key + "=" + URLEncoder.encode(map.get(key).toString(), HttpConstant.ENCODE));
                // + paramBundle.getString(key));
            }
        }
    } else if (paramObject instanceof List && ((List) paramObject).get(0) instanceof NameValuePair) {
        // if (paramObject instanceof List) {
        // List list = (List) paramObject;
        // Object object = list.get(0);
        // if (object instanceof NameValuePair) {
        boolean isFirst = true;
        for (NameValuePair nameValuePair : (List<NameValuePair>) paramObject) {
            if (isFirst)
                isFirst = false;
            else
                sb.append("&");
            // Object object;
            sb.append(nameValuePair.getName() + "="
                    + URLEncoder.encode(nameValuePair.getValue(), HttpConstant.ENCODE));
            // + paramBundle.getString(key));
        }
    } else {
        // sb.append("&");
        // Object object;
        sb.append(HttpConstant.DEFAULT_KEY_REQUEST_PARAM + "="
                + URLEncoder.encode(this.jsonManager.getJson(paramObject), HttpConstant.ENCODE));
    }
    return sb.toString();
}