Example usage for android.os Bundle get

List of usage examples for android.os Bundle get

Introduction

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

Prototype

@Nullable
public Object get(String key) 

Source Link

Document

Returns the entry with the given key as an object.

Usage

From source file:de.ub0r.android.smsdroid.SmsReceiver.java

static void handleOnReceive(final BroadcastReceiver receiver, final Context context, final Intent intent) {
    final String action = intent.getAction();
    Log.d(TAG, "onReceive(context, ", action, ")");
    final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakelock.acquire();/*  w  ww  .  ja  va 2  s  . c  om*/
    Log.i(TAG, "got wakelock");
    Log.d(TAG, "got intent: ", action);
    try {
        Log.d(TAG, "sleep(", SLEEP, ")");
        Thread.sleep(SLEEP);
    } catch (InterruptedException e) {
        Log.d(TAG, "interrupted in spinlock", e);
        e.printStackTrace();
    }
    String text;
    if (SenderActivity.MESSAGE_SENT_ACTION.equals(action)) {
        handleSent(context, intent, receiver.getResultCode());
    } else {
        boolean silent = false;

        if (shouldHandleSmsAction(context, action)) {
            Bundle b = intent.getExtras();
            assert b != null;
            Object[] messages = (Object[]) b.get("pdus");
            SmsMessage[] smsMessage = new SmsMessage[messages.length];
            int l = messages.length;
            for (int i = 0; i < l; i++) {
                smsMessage[i] = SmsMessage.createFromPdu((byte[]) messages[i]);
            }
            text = null;
            if (l > 0) {
                // concatenate multipart SMS body
                StringBuilder sbt = new StringBuilder();
                for (int i = 0; i < l; i++) {
                    sbt.append(smsMessage[i].getMessageBody());
                }
                text = sbt.toString();

                // ! Check in blacklist db - filter spam
                String s = smsMessage[0].getDisplayOriginatingAddress();

                // this code is used to strip a forwarding agent and display the orginated number as sender
                final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                if (prefs.getBoolean(PreferencesActivity.PREFS_FORWARD_SMS_CLEAN, false)
                        && text.contains(":")) {
                    Pattern smsPattern = Pattern.compile("([0-9a-zA-Z+]+):");
                    Matcher m = smsPattern.matcher(text);
                    if (m.find()) {
                        s = m.group(1);
                        Log.d(TAG, "found forwarding sms number: (", s, ")");
                        // now strip the sender from the message
                        Pattern textPattern = Pattern.compile("^[0-9a-zA-Z+]+: (.*)");
                        Matcher m2 = textPattern.matcher(text);
                        if (text.contains(":") && m2.find()) {
                            text = m2.group(1);
                            Log.d(TAG, "stripped the message");
                        }
                    }
                }

                final SpamDB db = new SpamDB(context);
                db.open();
                if (db.isInDB(smsMessage[0].getOriginatingAddress())) {
                    Log.d(TAG, "Message from ", s, " filtered.");
                    silent = true;
                } else {
                    Log.d(TAG, "Message from ", s, " NOT filtered.");
                }
                db.close();

                if (action.equals(ACTION_SMS_NEW)) {
                    // API19+: save message to the database
                    ContentValues values = new ContentValues();
                    values.put("address", s);
                    values.put("body", text);
                    context.getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
                    Log.d(TAG, "Insert SMS into database: ", s, ", ", text);
                }
            }
            updateNotificationsWithNewText(context, text, silent);
        } else if (ACTION_MMS_OLD.equals(action) || ACTION_MMS_MEW.equals(action)) {
            text = MMS_BODY;
            // TODO API19+ MMS code
            updateNotificationsWithNewText(context, text, silent);
        }
    }
    wakelock.release();
    Log.i(TAG, "wakelock released");
}

From source file:com.amazon.cordova.plugin.PushPlugin.java

private static JSONObject convertBundleToJson(Bundle extras) {
    if (extras == null) {
        return null;
    }//ww  w .  ja  v a 2s  . c o  m

    try {
        JSONObject json;
        json = new JSONObject().put(EVENT, MESSAGE);

        JSONObject jsondata = new JSONObject();
        Iterator<String> it = extras.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            Object value = extras.get(key);

            // System data from Android
            if (key.equals(FOREGROUND)) {
                json.put(key, extras.getBoolean(FOREGROUND));
            } else if (key.equals(COLDSTART)) {
                json.put(key, extras.getBoolean(COLDSTART));
            } else {
                // we encourage put the message content into message value
                // when server send out notification
                if (key.equals(MESSAGE)) {
                    json.put(key, value);
                }

                if (value instanceof String) {
                    // Try to figure out if the value is another JSON object

                    String strValue = (String) value;
                    if (strValue.startsWith("{")) {
                        try {
                            JSONObject json2 = new JSONObject(strValue);
                            jsondata.put(key, json2);
                        } catch (Exception e) {
                            jsondata.put(key, value);
                        }
                        // Try to figure out if the value is another JSON
                        // array
                    } else if (strValue.startsWith("[")) {
                        try {
                            JSONArray json2 = new JSONArray(strValue);
                            jsondata.put(key, json2);
                        } catch (Exception e) {
                            jsondata.put(key, value);
                        }
                    } else {
                        jsondata.put(key, value);
                    }
                }
            } // while
        }
        json.put(PAYLOAD, jsondata);
        LOG.v(TAG, "extrasToJSON: " + json.toString());

        return json;
    } catch (JSONException e) {
        LOG.e(TAG, "extrasToJSON: JSON exception");
    }
    return null;
}

From source file:com.cloudzilla.fb.FacebookServiceProxy.java

private static String toString(Bundle bundle) {
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    for (String key : bundle.keySet()) {
        sb.append(key + ":" + bundle.get(key) + ",");
    }/*from  w  ww.  ja  v a  2 s .c  o m*/
    sb.append("}");
    return sb.toString();
}

From source file:com.example.jumpnote.android.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public static void ensureHasTokenWithUI(Activity activity, Account account,
        final EnsureHasTokenWithUICallback callback) {
    AccountManager am = AccountManager.get(activity);
    am.getAuthToken(account, APPENGINE_SERVICE_NAME, null, activity, new AccountManagerCallback<Bundle>() {
        public void run(AccountManagerFuture<Bundle> authBundleFuture) {
            Bundle authBundle = null;
            try {
                authBundle = authBundleFuture.getResult();
            } catch (OperationCanceledException e) {
                callback.onAuthDenied();
                return;
            } catch (AuthenticatorException e) {
                callback.onError(e);//from   w w  w.j  av  a2s .c  om
                return;
            } catch (IOException e) {
                callback.onError(e);
                return;
            }

            if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                callback.onHasToken((String) authBundle.get(AccountManager.KEY_AUTHTOKEN));
            } else {
                callback.onError(
                        new IllegalStateException("No auth token available, but operation not canceled."));
            }
        }
    }, null);
}

From source file:Main.java

public static void intentToAndroidLayoutMapper(Class<?> classObj, Intent intent, String prefixStr,
        Activity view) {/* w  ww.ja  va  2  s. c  om*/

    Bundle map = intent.getExtras();

    for (Object keyObj : map.keySet().toArray()) {
        String keyStr = keyObj.toString();
        Field fieldObj = null;
        try {
            fieldObj = classObj.getField(prefixStr + "_" + keyStr);
        } catch (NoSuchFieldException e) {
            continue;
        }
        Object layoutObj = null;
        try {
            layoutObj = fieldObj.get(fieldObj);
        } catch (IllegalAccessException e) {
            continue;
        }
        Integer layoutIntvalue = (Integer) layoutObj;

        View selectedView = view.findViewById(layoutIntvalue);

        if (selectedView instanceof TextView) {
            TextView textView = (TextView) selectedView;
            textView.setText((String) map.get(keyStr));
        } else if (selectedView instanceof ImageView) {
            ImageView imageView = (ImageView) selectedView;

        }

    }

}

From source file:com.gcm.client.GcmHelper.java

/**
 * A debugging method which helps print the entire bundle
 *
 * @param data instance of the {@link Bundle} which needs to be printed
 *///ww w. java  2s  .  com
static void printBundle(Bundle data) {
    try {
        if (null == data) {
            Log.d(TAG, "printBundle:No extras to log");
            return;
        }
        Set<String> ketSet = data.keySet();
        if (null == ketSet || ketSet.isEmpty())
            return;
        Log.d(TAG, "------Start of bundle extras------");
        for (String key : ketSet) {
            Object obj = data.get(key);
            if (null != obj) {
                Log.d(TAG, "[ " + key + " = " + obj.toString() + " ]");
            }
        }
        Log.d(TAG, "-------End of bundle extras-------");
    } catch (Exception e) {
        if (DEBUG_ENABLED)
            Log.e(TAG, "printBundle", e);
    }
}

From source file:com.wareninja.android.opensource.oauth2login.common.Utils.java

/**
 * Generate the multi-part post body providing the parameters and boundary
 * string/*from w  w  w.j  a  v a2 s. com*/
 * 
 * @param parameters the parameters need to be posted
 * @param boundary the random string as boundary
 * @return a string of the post body
 */
public static String encodePostBody(Bundle parameters, String boundary) {
    if (parameters == null)
        return "";
    StringBuilder sb = new StringBuilder();

    for (String key : parameters.keySet()) {

        /*//YG:removed this from sdk
        try{
         if (parameters.getByteArray(key) != null) {
            continue;
         }
        }catch(Exception ex){}
        */

        sb.append("Content-Disposition: form-data; name=\"" + key +
        //"\"\r\n\r\n" + parameters.getString(key));
                "\"\r\n\r\n" + parameters.get(key));//to avoid type clash
        sb.append("\r\n" + "--" + boundary + "\r\n");
    }

    return sb.toString();
}

From source file:com.commontime.plugin.notification.Notification.java

private static JSONObject convertBundleToJson(Bundle extras) {
    try {//from   w w  w.j  ava 2  s  .c om
        JSONObject json;
        json = new JSONObject().put("event", "message");

        Iterator<String> it = extras.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            Object value = extras.get(key);

            // System data from Android
            if (key.equals("from") || key.equals("collapse_key")) {
                json.put(key, value);
            } else if (key.equals("foreground")) {
                json.put(key, extras.getBoolean("foreground"));
            } else if (key.equals("coldstart")) {
                json.put(key, extras.getBoolean("coldstart"));
            } else if (key.equals("title")) {
                json.put(key, extras.getString("title"));
            } else if (key.equals("message")) {
                json.put(key, extras.getString("message"));
            } else if (key.equals("payload")) {
                createPayloadObject(json, (String) value);
            } else {
                if (value instanceof String) {
                    createPayloadObject(json, (String) value);
                }
            }
        } // while

        json.put("service", "GCM");

        return json;
    } catch (JSONException e) {
    }
    return null;
}

From source file:com.github.michalbednarski.intentslab.browser.ComponentInfoFragment.java

public static CharSequence dumpMetaData(final Context context, final String packageName, Bundle metaData) {
    FormattedTextBuilder text = new FormattedTextBuilder();
    Context foreignContext = null;
    try {/*ww  w  .j a  v  a 2 s.co  m*/
        foreignContext = context.createPackageContext(packageName, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    if (metaData != null && !metaData.isEmpty()) {
        text.appendHeader(context.getString(R.string.metadata_header));
        for (String key : metaData.keySet()) {
            Object value = metaData.get(key);
            if (value instanceof Integer) {
                // TODO resource?
                if (foreignContext != null) {
                    text.appendValueNoNewLine(key, value.toString());
                    // Integers can point to resources
                    final int resId = (Integer) value;
                    if (resId == 0) {
                        continue;
                    }

                    // [View as XML] link
                    try {
                        foreignContext.getResources().getXml(resId);
                        text.appendClickable(context.getString(R.string.view_as_xml_resource),
                                new ClickableSpan() {
                                    @Override
                                    public void onClick(View widget) {
                                        context.startActivity(new Intent(context, SingleFragmentActivity.class)
                                                .putExtra(SingleFragmentActivity.EXTRA_FRAGMENT,
                                                        XmlViewerFragment.class.getName())
                                                .putExtra(XmlViewerFragment.ARG_PACKAGE_NAME, packageName)
                                                .putExtra(XmlViewerFragment.ARG_RESOURCE_ID, resId));
                                    }
                                });
                    } catch (Resources.NotFoundException ignored) {
                    }
                }
                // Other types
            } else if (value instanceof Float) {
                text.appendValueNoNewLine(key,
                        value.toString() + (((Float) value) % 1f == 0f ? "" : " (float)"));
            } else if (value instanceof Boolean) {
                text.appendValueNoNewLine(key, value.toString());
            } else if (value instanceof String) {
                text.appendValueNoNewLine(key, "\"" + value + "\"");
            }
        }
    }
    return text.getText();
}

From source file:com.enefsy.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String//from   ww  w  . jav  a2 s.  com
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            Object parameter = params.get(key);
            if (parameter instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) parameter);
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

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

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((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 = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}