Example usage for android.os Bundle putByteArray

List of usage examples for android.os Bundle putByteArray

Introduction

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

Prototype

@Override
public void putByteArray(@Nullable String key, @Nullable byte[] value) 

Source Link

Document

Inserts a byte array value into the mapping of this Bundle, replacing any existing value for the given key.

Usage

From source file:com.nonstop.android.SoC.BluetoothChat.BluetoothChat.java

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (D)//www.  java 2  s  .  c  o m
        Log.d(TAG, "onActivityResult " + resultCode);
    switch (requestCode) {
    case REQUEST_CONNECT_DEVICE_SECURE:
        // When DeviceListActivity returns with a device to connect
        if (resultCode == Activity.RESULT_OK) {
            connectDevice(data, true);
        }
        break;
    case REQUEST_CONNECT_DEVICE_INSECURE:
        // When DeviceListActivity returns with a device to connect
        if (resultCode == Activity.RESULT_OK) {
            connectDevice(data, false);
        }
        break;
    case REQUEST_ENABLE_BT:
        // When the request to enable Bluetooth returns
        if (resultCode == Activity.RESULT_OK) {
            // Bluetooth is now enabled, so set up a chat session
            setupChat();
        } else {
            // User did not enable Bluetooth or an error occured
            Log.d(TAG, "BT not enabled");
            Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
            finish();
        }
        /*
         * if this is the activity result from authorization flow, do a call
         * back to authorizeCallback Source Tag: login_tag
         */
    case AUTHORIZE_ACTIVITY_RESULT_CODE: {
        Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
        break;
    }
    /*
     * if this is the result for a photo picker from the gallery, upload the
     * image after scaling it. You can use the Utility.scaleImage() function
     * for scaling
     */
    case PICK_EXISTING_PHOTO_RESULT_CODE: {
        if (resultCode == Activity.RESULT_OK) {
            Uri photoUri = data.getData();
            if (photoUri != null) {
                Bundle params = new Bundle();
                try {
                    params.putByteArray("photo", Utility.scaleImage(getApplicationContext(), photoUri));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                params.putString("caption", "NonstopSoC");
                Utility.mAsyncRunner.request("me/photos", params, "POST", new PhotoUploadListener(), null);
            } else {
                Toast.makeText(getApplicationContext(), "Error selecting image from the gallery.",
                        Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "No image selected for upload.", Toast.LENGTH_SHORT).show();
        }
        break;

    }
    }
}

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 w w w  .  j a va  2s .c  om*/

    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:com.geecko.QuickLyric.MainActivity.java

public void updateLyricsFragment(int outAnim, int inAnim, boolean transition, Lyrics lyrics) {
    LyricsViewFragment lyricsViewFragment = (LyricsViewFragment) getFragmentManager()
            .findFragmentByTag(LYRICS_FRAGMENT_TAG);
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.setCustomAnimations(inAnim, outAnim, inAnim, outAnim);
    Fragment activeFragment = getDisplayedFragment(getActiveFragments());
    if (lyricsViewFragment != null && lyricsViewFragment.getView() != null) {
        SharedPreferences preferences = getSharedPreferences("current_music", Context.MODE_PRIVATE);
        String artist = preferences.getString("artist", null);
        String track = preferences.getString("track", null);
        if (lyrics.isLRC()
                && !(lyrics.getOriginalArtist().equals(artist) && lyrics.getOriginalTrack().equals(track))) {
            LrcView parser = new LrcView(this, null);
            parser.setOriginalLyrics(lyrics);
            parser.setSourceLrc(lyrics.getText());
            lyrics = parser.getStaticLyrics();
        }/*from w  ww. j  a v a 2  s . c o m*/
        lyricsViewFragment.update(lyrics, lyricsViewFragment.getView(), true);
        if (transition) {
            fragmentTransaction.hide(activeFragment).show(lyricsViewFragment);
            prepareAnimations(activeFragment);
            prepareAnimations(lyricsViewFragment);
        }
        showRefreshFab(true);
        lyricsViewFragment.expandToolbar();
    } else {
        Bundle lyricsBundle = new Bundle();
        try {
            lyricsBundle.putByteArray("lyrics", lyrics.toBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        lyricsViewFragment = new LyricsViewFragment();
        lyricsViewFragment.setArguments(lyricsBundle);
        if (!(activeFragment instanceof LyricsViewFragment) && activeFragment != null)
            fragmentTransaction.hide(activeFragment).add(id.main_fragment_container, lyricsViewFragment,
                    LYRICS_FRAGMENT_TAG);
        else
            fragmentTransaction.replace(id.main_fragment_container, lyricsViewFragment, LYRICS_FRAGMENT_TAG);
    }
    fragmentTransaction.commitAllowingStateLoss();
}

From source file:com.ijiaban.yinxiang.MainActivity.java

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    if (mGeneratedBitmap != null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        mGeneratedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bytes = stream.toByteArray();
        savedInstanceState.putByteArray(STORED_IMAGE, bytes);
    } else {//from w  ww . j av a2  s  . c o  m
        savedInstanceState.putByteArray(STORED_IMAGE, null);
    }

    savedInstanceState.putParcelable(STORED_CONTACT, mContact);
    savedInstanceState.putBoolean(STORED_PICKED, mHasPickedContact);
    savedInstanceState.putInt(STORED_WIDTH, mScreenWidthInPixels);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
    Log.d("MainActivity", "onSaveInstanceState()");
}

From source file:com.github.google.beaconfig.BeaconConfigActivity.java

@Override
public void slotDataChanged(final int slot, final byte[] newSlotData) {
    try {//w  w  w .  ja  v  a  2s. c  o  m
        Log.d(TAG, "New slot data: " + Arrays.toString(newSlotData));
        gattClient.writeActiveSlot(slot);
        gattClient.writeAdvSlotData(newSlotData);
        byte[] newlyReadSlotData = gattClient.readAdvSlotData();
        Bundle newSlotDataBundle = new Bundle();
        changeTabName(slot + 1, newlyReadSlotData);
        newSlotDataBundle.putByteArray(Constants.SLOT_DATA, newlyReadSlotData);
        slotsAdapter.getItem(slot + 1).updateInformation(newSlotDataBundle);
    } catch (GattClientException e) {
        Log.d(TAG, "Gatt Client Error when writing slot data to beacon", e);
        displayConnectionFailScreen("Something went wrong when writing slot data to beacon");
    } catch (GattOperationException e) {
        Log.d(TAG, "Gatt Operation Error when writing slot data to beacon", e);
        displayConnectionFailScreen("Something went wrong when writing slot data to beacon");
    }
}

From source file:com.concavenp.artistrymuse.fragments.SearchResultFragment.java

/**
 * Save off the User entered search string.
 *
 * @param outState - The bundle that will be presented to this fragment upon re-creation
 *//*from  w w w.  j a v a 2 s .  c  o m*/
@Override
public void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    outState.putInt(FLIP_ACTIVE_SEARCH_STRING + getDatabaseNameFromType(), mFlipper.getDisplayedChild());

    try {
        switch (mType) {
        case USERS: {
            List<UserResponseHit> list = mUsersAdapter.getData();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(list);
            outState.putByteArray(SEARCH_STRING + getDatabaseNameFromType(), baos.toByteArray());
            break;
        }
        case PROJECTS: {
            List<ProjectResponseHit> list = mProjectsAdapter.getData();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(list);
            outState.putByteArray(SEARCH_STRING + getDatabaseNameFromType(), baos.toByteArray());
            break;
        }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.github.google.beaconfig.BeaconConfigActivity.java

/**
 * Reads information about the beacon from the gatt client. It creates a fragment
 * for each slot of the beacon and puts it in the tab layout. Then all the available information
 * about this slot is read and displayed on the screen
 *
 * All operations do not involve UI are done on the background thread
 *///from  ww w.  j  ava  2  s.  co m
private void setUpFragments() {
    executor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                byte[] data = gattClient.readBroadcastCapabilities();
                capabilities = new BroadcastCapabilities(data);

                Bundle globalDataBundle = new Bundle();
                globalDataBundle.putByteArray(Constants.BROADCAST_CAPABILITIES, data);
                globalDataBundle.putString(Constants.BEACON_ADDRESS, address);
                globalDataBundle.putString(Constants.BEACON_NAME, name);

                byte[] remainConnectable = gattClient.readRemainConnectable();
                globalDataBundle.putByte(Constants.REMAIN_CONNECTABLE, remainConnectable[0]);

                if (!capabilities.isVariableTxPowerSupported()) {
                    String radioTxPower = Integer.toString(gattClient.readRadioTxPower()[0]);
                    String advTxPower = Integer.toString(gattClient.readAdvertisedTxPower()[0]);
                    globalDataBundle.putString(Constants.TX_POWER, radioTxPower);
                    globalDataBundle.putString(Constants.ADV_POWER, advTxPower);
                }
                if (!capabilities.isVariableAdvSupported()) {
                    String advInterval = Integer.toString(Utils.toInt(gattClient.readAdvertisingInterval()));
                    globalDataBundle.putString(Constants.ADV_INTERVAL, advInterval);
                }

                GlobalFragment globalFragment = GlobalFragment.newInstance(globalDataBundle);
                slotsAdapter.addFragment(globalFragment);

                for (int i = 0; i < capabilities.getMaxSupportedTotalSlots(); i++) {
                    gattClient.writeActiveSlot(i);
                    final Bundle slotInfoBundle = new Bundle();
                    final byte[] slotData = gattClient.readAdvSlotData();
                    slotInfoBundle.putByteArray(Constants.SLOT_DATA, slotData);

                    if (capabilities.isVariableTxPowerSupported()) {
                        String radioTxPower = Integer.toString(gattClient.readRadioTxPower()[0]);
                        String advTxPower = Integer.toString(gattClient.readAdvertisedTxPower()[0]);
                        slotInfoBundle.putString(Constants.TX_POWER, radioTxPower);
                        slotInfoBundle.putString(Constants.ADV_POWER, advTxPower);
                    }

                    if (capabilities.isVariableAdvSupported()) {
                        String advInterval = Integer
                                .toString(Utils.toInt(gattClient.readAdvertisingInterval()));
                        slotInfoBundle.putString(Constants.ADV_INTERVAL, advInterval);
                    }

                    slotInfoBundle.putByteArray(Constants.BROADCAST_CAPABILITIES, data);

                    slotInfoBundle.putInt(Constants.SLOT_NUMBER, i);

                    slotsAdapter.createNewFragment(slotInfoBundle);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            slotsAdapter.notifyDataSetChanged();
                        }
                    });
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        viewPager.setOffscreenPageLimit(capabilities.getMaxSupportedTotalSlots());
                        setTabTitles();
                        enableDisplay();
                        findViewById(R.id.tab_layout).setVisibility(View.VISIBLE);
                    }
                });
            } catch (GattClientException e) {
                Log.d(TAG, "Gatt Client Error when getting information from beacon", e);
                displayConnectionFailScreen("Something went wrong when getting information " + "from beacon");
            } catch (GattOperationException e) {
                Log.d(TAG, "Gatt Operation Error when getting information from beacon", e);
                displayConnectionFailScreen("Something went wrong when getting information " + "from beacon");
            }

        }
    });
}

From source file:com.geecko.QuickLyric.MainActivity.java

public void updateLyricsFragment(int outAnim, String... params) { // Should only be called from SearchFragment or IdDecoder
    String artist = params[0];//w  w  w. j  a  v a  2 s  . c  om
    String song = params[1];
    String url = null;
    if (params.length > 2)
        url = params[2];
    LyricsViewFragment lyricsViewFragment = (LyricsViewFragment) getFragmentManager()
            .findFragmentByTag(LYRICS_FRAGMENT_TAG);
    if (lyricsViewFragment != null)
        lyricsViewFragment.fetchLyrics(artist, song, url);
    else {
        Lyrics lyrics = new Lyrics(Lyrics.SEARCH_ITEM);
        lyrics.setArtist(artist);
        lyrics.setTitle(song);
        lyrics.setURL(url);
        Bundle lyricsBundle = new Bundle();
        try {
            if (artist != null && song != null)
                lyricsBundle.putByteArray("lyrics", lyrics.toBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        lyricsViewFragment = new LyricsViewFragment();
        lyricsViewFragment.setArguments(lyricsBundle);

        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.setCustomAnimations(R.animator.slide_in_start, outAnim, R.animator.slide_in_start,
                outAnim);
        Fragment activeFragment = getDisplayedFragment(getActiveFragments());
        if (activeFragment != null) {
            prepareAnimations(activeFragment);
            fragmentTransaction.hide(activeFragment);
        }
        fragmentTransaction.add(id.main_fragment_container, lyricsViewFragment, LYRICS_FRAGMENT_TAG);
        lyricsViewFragment.isActiveFragment = true;
        fragmentTransaction.commit();
    }
    if (drawer instanceof DrawerLayout && !mDrawerToggle.isDrawerIndicatorEnabled()) {
        mDrawerToggle.setDrawerIndicatorEnabled(true);
        ((DrawerLayout) drawer).setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }
}

From source file:com.sina.weibo.sdk.demo.openapi.user_homeActivity.java

/**
 * @see {@link Activity#onCreate}/*from w w  w  .  j  a  va 2 s.com*/
 */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.weibo_item);
    //mLogoutButton = (Button) findViewById(R.id.logout);

    // ??? Token
    mAccessToken = AccessTokenKeeper.readAccessToken(this);
    // ???
    mUsersAPI = new UsersAPI(this, Constants.APP_KEY, mAccessToken);
    mStatusesAPI = new StatusesAPI(this, Constants.APP_KEY, mAccessToken);
    getUserInfo();

    //
    this.findViewById(R.id.home_page).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(user_homeActivity.this, mytestActivity.class));
        }
    });
    this.findViewById(R.id.send_page).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(user_homeActivity.this, WBStatus_sendAPIActivity.class));
        }
    });
    //
    //
    this.findViewById(R.id.fllowers).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(user_homeActivity.this, user_fllowers.class));
        }
    });
    //?
    this.findViewById(R.id.friends).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(user_homeActivity.this, user_friends.class));
        }
    });
    //
    mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Constants.APP_KEY);
    mWeiboShareAPI.registerApp();
    shearMessageReceiver = new ShearMessageReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_SHEAR_RESULT);
    registerReceiver(shearMessageReceiver, filter);
    this.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mWeiboShareAPI.isWeiboAppInstalled()) {
                Toast.makeText(user_homeActivity.this, "", Toast.LENGTH_LONG).show();
            }
            //
            if (true) {
                Bundle bundle = new Bundle();
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo);
                bundle.putString(WBConstants.SDK_WEOYOU_SHARETITLE, "share our app to others");
                bundle.putString(WBConstants.SDK_WEOYOU_SHAREDESC, "say something...");
                bundle.putString(WBConstants.SDK_WEOYOU_SHAREURL, "http://github/laterlater.com");
                bundle.putString("shareBackScheme", "weiboDemo://share");
                bundle.putString(SHARE_APP_NAME, "app name");
                bundle.putString(PARAM_SHARE_FROM, EXTEND_SHARE_570);
                bundle.putByteArray(WBConstants.SDK_WEOYOU_SHAREIMAGE, bitMapToBytes(bitmap));
                mWeiboShareAPI.shareMessageToWeiyou(user_homeActivity.this, bundle);
            } else {
                Toast.makeText(user_homeActivity.this, "?", Toast.LENGTH_LONG).show();
            }
        }
    });
    this.findViewById(R.id.logout).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mAccessToken != null && mAccessToken.isSessionValid()) {
                new LogoutAPI(user_homeActivity.this, Constants.APP_KEY, mAccessToken)
                        .logout(mLogoutRequestListener);
            }
        }
    });
}

From source file:com.mbientlab.metawear.app.ModuleActivity.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (device != null) {
        outState.putParcelable(EXTRA_BLE_DEVICE, device);
    }// w  w w.  java 2 s  . c o  m
    if (moduleFragment != null) {
        getSupportFragmentManager().putFragment(outState, "mContent", moduleFragment);
    }

    outState.putInt(Extra.TAP_TYPE, tapType);
    outState.putInt(Extra.TAP_AXIS, tapAxis);
    outState.putInt(Extra.SHAKE_AXIS, shakeAxis);
    outState.putInt(Extra.DATA_RANGE, dataRange);
    outState.putInt(Extra.SAMPLING_RATE, samplingRate);
    outState.putBoolean(Extra.FF_MOVEMENT, ffMovement);
    outState.putBoolean(Extra.NEW_FIRMWARE, newFirmware);
    outState.putByteArray(Extra.SAMPLING_CONFIG_BYTES, samplingConfigBytes);
    outState.putSerializable(Extra.POLLED_DATA, polledData);
}