Example usage for android.os Bundle isEmpty

List of usage examples for android.os Bundle isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if the mapping of this Bundle is empty, false otherwise.

Usage

From source file:com.google.android.gcm.demo.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    setContentView(R.layout.activity_main);
    mLogger = new Logger(this);
    mLogsUI = (TextView) findViewById(R.id.logs);
    mLoggerCallback = new BroadcastReceiver() {
        @Override//from   w w w.  ja v  a2s. c o m
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
            case LoggingService.ACTION_CLEAR_LOGS:
                mLogsUI.setText("");
                break;
            case LoggingService.ACTION_LOG:
                StringBuilder stringBuilder = new StringBuilder();
                String newLog = intent.getStringExtra(LoggingService.EXTRA_LOG_MESSAGE);
                String oldLogs = Html.toHtml(new SpannableString(mLogsUI.getText()));
                appendFormattedLogLine(newLog, stringBuilder);
                stringBuilder.append(oldLogs);
                mLogsUI.setText(Html.fromHtml(stringBuilder.toString()));
                List<Fragment> fragments = getSupportFragmentManager().getFragments();
                for (Fragment fragment : fragments) {
                    if (fragment instanceof RefreshableFragment && fragment.isVisible()) {
                        ((RefreshableFragment) fragment).refresh();
                    }
                }
                break;
            }
        }
    };

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerView = (FrameLayout) findViewById(R.id.navigation_drawer);
    mDrawerMenu = (ListView) findViewById(R.id.navigation_drawer_menu);
    mDrawerScrim = findViewById(R.id.navigation_drawer_scrim);

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    TypedArray colorPrimaryDark = getTheme().obtainStyledAttributes(new int[] { R.attr.colorPrimaryDark });
    mDrawerLayout.setStatusBarBackgroundColor(colorPrimaryDark.getColor(0, 0xFF000000));
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    colorPrimaryDark.recycle();

    ImageView drawerHeader = new ImageView(this);
    drawerHeader.setImageResource(R.drawable.drawer_gcm_logo);
    mDrawerMenu.addHeaderView(drawerHeader);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // Set the drawer width accordingly with the guidelines: window_width - toolbar_height.
        toolbar.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View view, int left, int top, int right, int bottom, int oldLeft,
                    int oldTop, int oldRight, int oldBottom) {
                if (left == 0 && top == 0 && right == 0 && bottom == 0) {
                    return;
                }
                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);
                float logicalDensity = metrics.density;
                int maxWidth = (int) Math.ceil(320 * logicalDensity);
                DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mDrawerView.getLayoutParams();
                int newWidth = view.getWidth() - view.getHeight();
                params.width = (newWidth > maxWidth ? maxWidth : newWidth);
                mDrawerView.setLayoutParams(params);
            }
        });
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        mDrawerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
            @Override
            public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                // Set scrim height to match status bar height.
                mDrawerScrim.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                        insets.getSystemWindowInsetTop()));
                return insets;
            }
        });
    }

    int activeItemIndicator = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            ? android.R.layout.simple_list_item_activated_1
            : android.R.layout.simple_list_item_checked;

    mMainMenu = new MainMenu(this);
    mDrawerMenu.setOnItemClickListener(this);
    mDrawerMenu.setAdapter(new ArrayAdapter<>(getSupportActionBar().getThemedContext(), activeItemIndicator,
            android.R.id.text1, mMainMenu.getEntries()));

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            // The user learned how to open the drawer. Do not open it for him anymore.
            getAppPreferences().edit().putBoolean(PREF_OPEN_DRAWER_AT_STARTUP, false).apply();
            super.onDrawerOpened(drawerView);
        }
    };

    boolean activityResumed = (savedState != null);
    boolean openDrawer = getAppPreferences().getBoolean(PREF_OPEN_DRAWER_AT_STARTUP, true);
    int lastScreenId = getAppPreferences().getInt(PREF_LAST_SCREEN_ID, 0);
    selectItem(lastScreenId);
    if (!activityResumed && openDrawer) {
        mDrawerLayout.openDrawer(mDrawerView);
    }
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    /*
     * Here we check if the Activity was created by the user clicking on one of our GCM
     * notifications:
     * 1. Check if the action of the intent used to launch the Activity.
     * 2. Print out any additional data sent with the notification. This is included as extras
     *  on the intent.
     */
    Intent launchIntent = getIntent();
    if ("gcm_test_app_notification_click_action".equals(launchIntent.getAction())) {
        Bundle data = launchIntent.getExtras();
        data.isEmpty(); // Force the bundle to unparcel so that toString() works
        String format = getResources().getString(R.string.notification_intent_received);
        mLogger.log(Log.INFO, String.format(format, data));
    }
}

From source file:com.amazon.rvspeedtest.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.i(TAG, "onHandleIntent called");
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String requestId = extras.getString("requestId");
    // 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
        /*// w ww  .  ja v a  2 s. c  o m
         * 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 downloadSpeed = testDownloadSpeed();
            //sendSpeedToServer(downloadSpeed, requestId);

            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            sendNotification("Received message from Alexa");
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:eu.nerdz.app.messenger.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {

    Log.d(TAG, "Received message!");

    if (this.mNotificationManager == null) {
        this.mNotificationManager = (NotificationManager) NerdzMessenger.context
                .getSystemService(Context.NOTIFICATION_SERVICE);
    }//www.j a  v  a 2 s .co m

    if (this.mLocalBroadcastManager == null) {
        this.mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    }

    Bundle extras = intent.getExtras();

    if (extras == null) {
        return;
    }

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {

        if (!GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

            Log.w(TAG, "Unknown message type " + messageType);

        } else {

            this.notifyUser(extras.getString("messageFrom"),
                    Integer.parseInt(extras.getString("messageFromId")), extras.getString("messageBody"));

        }

    }

    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:vn.seasoft.sachcuatui.GCMService.GCMIntentService.java

@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);

    String messageReceived = "";
    String jsonBook = "";
    if (!extras.isEmpty()) { // has effect of unparcelling Bundle

        messageReceived = extras.getString("message");
        jsonBook = extras.getString("book");
        /*//from   w w  w.  j a va 2s. c  o  m
         * 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)) {

            // Post notification of received message.
            if (messageReceived != null) {
                if (!messageReceived.trim().equals("")) {
                    messageReceived = messageReceived.trim();
                    messageReceived = messageReceived.replace("{you}",
                            "Bn " + mSharedPreferences.getUserDisplay(getApplicationContext()));

                    Book book = null;
                    if (jsonBook != null) {
                        if (!jsonBook.equals("")) {
                            try {
                                JSONObject getJsonBook = new JSONObject(jsonBook);
                                JSONObject Obj = getJsonBook.getJSONObject("data");
                                book = new Book();
                                book.setIdbook(Obj.getInt("idbook"));
                                book.setTitle(Obj.getString("title"));
                                book.setAuthor(Obj.getString("author"));
                                book.setSummary(Obj.getString("summary"));
                                book.setIdcategory(Obj.getInt("idcategory"));
                                book.setCountview(Obj.getInt("countview"));
                                book.setCountdownload(Obj.getInt("countdownload"));
                                if (!Obj.isNull("imagecover"))
                                    book.setImagecover(Obj.getString("imagecover").replace(" ", "%20"));
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                book = null;
                            }
                        }
                    }
                    sendNotification(messageReceived, book);
                }
            }
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.example.product.GcmIntentService.java

@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
        /*//from   ww  w .  j a v a  2 s  .  co m
         * 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)) {
            Log.e(TAG, "GCM_MESSAGE_TYPE_SEND_ERROR");
            //do nothing              
            //sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            Log.e(TAG, "GCM_MESSAGE_TYPE_DELETED");
            //do nothing            
            //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)) {

            //? ?? Notification? .              
            // 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.
            //sendNotification("Received: " + extras.toString());                
            //test sendNotification
            sendNotification(extras);

            Log.i(TAG, "Received: " + extras.toString());

            //??  
            if (!isScreenOn(this)) {

                Log.i(TAG, "screen is off");

                //test
                Intent popupIntent = new Intent(this, ActivityPopUp.class).putExtras(extras)
                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //  .
                this.startActivity(popupIntent);

            }
            //??  
            else {
                ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
                List<RunningTaskInfo> runList = am.getRunningTasks(10);
                ComponentName name = runList.get(0).topActivity;
                String className = name.getClassName();
                boolean isAppRunning = false;

                Log.i(TAG, "className ==" + className);
                //? ?? AcitivityPopUp ?
                if (className.equals("com.example.product.ActivityPopUp")) {
                    isAppRunning = true;
                }

                //?? ?
                if (isAppRunning == true) {
                    Log.i(TAG, "screen is off, but popup is on");

                    //test
                    Intent popupIntent = new Intent(this, ActivityPopUp.class).putExtras(extras)
                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    //  .
                    this.startActivity(popupIntent);
                    // ? ?  ? 
                }
                //? ? ? 
                else {

                    // ? ? ?  ? 

                }
            }

        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:br.com.ufc.palestrasufc.twitter.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * //  ww w .j a v a  2 s .  c  om
 * 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
 * @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);
    }
    Log.d("Twitter-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " TwitterAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // 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;
}

From source file:com.frublin.androidoauth2.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/* w w w.  jav  a2s.co  m*/
 * @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;

    url = url + "?" + encodeUrl(params);

    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FoursquareAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

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

        if (params.containsKey("oauth_token")) {
            String decoded_token = URLDecoder.decode(params.getString("oauth_token"));
            params.putString("oauth_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;
}

From source file:com.familygraph.android.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from w  ww.jav a 2  s  .c  o m*/
 * 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
 * @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);
    }
    Log.d("FamilyGraph-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FamilyGraphAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // 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 FamilyGraph
        // error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.qburst.android.linkedin.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * //from  w  w  w .  j  a v  a2s.c o  m
 * 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
 * @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);
    }
    Log.d("Twitter-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " LinkedInAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // 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;
}

From source file:br.random.util.facebookintegration.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/* w w  w.j a v a  2 s  .  co  m*/
 * @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);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    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()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // 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;
}