Example usage for android.os Bundle getByteArray

List of usage examples for android.os Bundle getByteArray

Introduction

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

Prototype

@Override
@Nullable
public byte[] getByteArray(@Nullable String key) 

Source Link

Document

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Usage

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 va2 s. c  o  m*/

    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:mobisocial.musubi.ui.FeedDetailsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
    setContentView(R.layout.feed_details);
    setTitle("Feed Details");
    mDb = new DatabaseManager(this);

    SQLiteOpenHelper helper = App.getDatabaseSource(this);
    mIdentitiesManager = new IdentitiesManager(helper);
    mContacts = new ContactListCursorAdapter(this, null);

    mFeedMembersView = (ListView) findViewById(R.id.feed_details_members_list);
    LayoutInflater inflater = getLayoutInflater();
    ViewGroup header = (ViewGroup) inflater.inflate(R.layout.feed_details_header, mFeedMembersView, false);
    mFeedMembersView.addHeaderView(header, null, false);
    mFeedMembersView.setTextFilterEnabled(true);
    mFeedMembersView.setFastScrollEnabled(true);
    mFeedMembersView.setOnItemClickListener(this);
    mFeedMembersView.setCacheColorHint(Color.WHITE);
    mFeedMembersView.setAdapter(mContacts);

    mNameEditText = (EditText) header.findViewById(R.id.feed_title_edittext);
    mBroadcastPassword = (EditText) header.findViewById(R.id.broadcast_password);
    mThumbnailView = (ImageView) header.findViewById(R.id.icon);

    String name = null;//  www  . j a v a 2s .  c o  m
    if (savedInstanceState != null) {
        name = savedInstanceState.getString("name");
        mThumbnailBytes = savedInstanceState.getByteArray("thumbnailBytes");
        mDetailsChanged = savedInstanceState.getBoolean("detailsChanged");
    } else {
        Long feedId = Long.parseLong(getIntent().getData().getLastPathSegment());
        MFeed feed = mDb.getFeedManager().lookupFeed(feedId);
        name = UiUtil.getFeedNameFromMembersList(mDb.getFeedManager(), feed);
        mThumbnailBytes = mDb.getFeedManager().getFeedThumbnailForId(feedId);
    }
    Spannable span = EmojiSpannableFactory.getInstance(this).newSpannable(name);
    mNameEditText.setText(span);
    mNameEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mDetailsChanged = true;
            refreshUI();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            EmojiSpannableFactory.getInstance(mContext).updateSpannable(s);
        }
    });

    getSupportLoaderManager().initLoader(0, null, this);
    refreshUI();
}

From source file:com.facebook.LegacyTokenCacheTest.java

@Test
public void testAllTypes() {
    Bundle originalBundle = new Bundle();

    putBoolean(BOOLEAN_KEY, originalBundle);
    putBooleanArray(BOOLEAN_ARRAY_KEY, originalBundle);
    putByte(BYTE_KEY, originalBundle);//  w ww . j a  v a2s. c  o m
    putByteArray(BYTE_ARRAY_KEY, originalBundle);
    putShort(SHORT_KEY, originalBundle);
    putShortArray(SHORT_ARRAY_KEY, originalBundle);
    putInt(INT_KEY, originalBundle);
    putIntArray(INT_ARRAY_KEY, originalBundle);
    putLong(LONG_KEY, originalBundle);
    putLongArray(LONG_ARRAY_KEY, originalBundle);
    putFloat(FLOAT_KEY, originalBundle);
    putFloatArray(FLOAT_ARRAY_KEY, originalBundle);
    putDouble(DOUBLE_KEY, originalBundle);
    putDoubleArray(DOUBLE_ARRAY_KEY, originalBundle);
    putChar(CHAR_KEY, originalBundle);
    putCharArray(CHAR_ARRAY_KEY, originalBundle);
    putString(STRING_KEY, originalBundle);
    putStringList(STRING_LIST_KEY, originalBundle);
    originalBundle.putSerializable(SERIALIZABLE_KEY, AccessTokenSource.FACEBOOK_APPLICATION_WEB);

    ensureApplicationContext();

    LegacyTokenHelper cache = new LegacyTokenHelper(RuntimeEnvironment.application);
    cache.save(originalBundle);

    LegacyTokenHelper cache2 = new LegacyTokenHelper(RuntimeEnvironment.application);
    Bundle cachedBundle = cache2.load();

    assertEquals(originalBundle.getBoolean(BOOLEAN_KEY), cachedBundle.getBoolean(BOOLEAN_KEY));
    assertArrayEquals(originalBundle.getBooleanArray(BOOLEAN_ARRAY_KEY),
            cachedBundle.getBooleanArray(BOOLEAN_ARRAY_KEY));
    assertEquals(originalBundle.getByte(BYTE_KEY), cachedBundle.getByte(BYTE_KEY));
    assertArrayEquals(originalBundle.getByteArray(BYTE_ARRAY_KEY), cachedBundle.getByteArray(BYTE_ARRAY_KEY));
    assertEquals(originalBundle.getShort(SHORT_KEY), cachedBundle.getShort(SHORT_KEY));
    assertArrayEquals(originalBundle.getShortArray(SHORT_ARRAY_KEY),
            cachedBundle.getShortArray(SHORT_ARRAY_KEY));
    assertEquals(originalBundle.getInt(INT_KEY), cachedBundle.getInt(INT_KEY));
    assertArrayEquals(originalBundle.getIntArray(INT_ARRAY_KEY), cachedBundle.getIntArray(INT_ARRAY_KEY));
    assertEquals(originalBundle.getLong(LONG_KEY), cachedBundle.getLong(LONG_KEY));
    assertArrayEquals(originalBundle.getLongArray(LONG_ARRAY_KEY), cachedBundle.getLongArray(LONG_ARRAY_KEY));
    assertEquals(originalBundle.getFloat(FLOAT_KEY), cachedBundle.getFloat(FLOAT_KEY),
            TestUtils.DOUBLE_EQUALS_DELTA);
    assertArrayEquals(originalBundle.getFloatArray(FLOAT_ARRAY_KEY),
            cachedBundle.getFloatArray(FLOAT_ARRAY_KEY));
    assertEquals(originalBundle.getDouble(DOUBLE_KEY), cachedBundle.getDouble(DOUBLE_KEY),
            TestUtils.DOUBLE_EQUALS_DELTA);
    assertArrayEquals(originalBundle.getDoubleArray(DOUBLE_ARRAY_KEY),
            cachedBundle.getDoubleArray(DOUBLE_ARRAY_KEY));
    assertEquals(originalBundle.getChar(CHAR_KEY), cachedBundle.getChar(CHAR_KEY));
    assertArrayEquals(originalBundle.getCharArray(CHAR_ARRAY_KEY), cachedBundle.getCharArray(CHAR_ARRAY_KEY));
    assertEquals(originalBundle.getString(STRING_KEY), cachedBundle.getString(STRING_KEY));
    assertListEquals(originalBundle.getStringArrayList(STRING_LIST_KEY),
            cachedBundle.getStringArrayList(STRING_LIST_KEY));
    assertEquals(originalBundle.getSerializable(SERIALIZABLE_KEY),
            cachedBundle.getSerializable(SERIALIZABLE_KEY));
}

From source file:com.google.blockly.android.control.BlocklyController.java

/**
 * Loads a Workspace state from an Android {@link Bundle}, previous saved in
 * {@link #onSaveSnapshot(Bundle)}./*from   w  ww .  j  av a 2 s  . c  om*/
 *
 * @param savedInstanceState The activity state Bundle passed into {@link Activity#onCreate} or
 *     {@link Activity#onRestoreInstanceState}.
 * @return True if a Blockly state was found and successfully loaded into the Controller.
 *     Otherwise, false.
 */
public boolean onRestoreSnapshot(@Nullable Bundle savedInstanceState) {
    Bundle blocklyState = (savedInstanceState == null) ? null
            : savedInstanceState.getBundle(SNAPSHOT_BUNDLE_KEY);
    if (blocklyState != null) {
        byte[] bytes = blocklyState.getByteArray(SERIALIZED_WORKSPACE_KEY);
        if (bytes == null) {
            // Ignore all other workspace variables.
            return false;
        }
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            loadWorkspaceContents(in);
        } catch (BlocklyParserException e) {
            // Ignore all other workspace state variables.
            Log.w(TAG, "Unable to restore Blockly state.", e);
            return false;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // Ignore.
            }
        }

        // TODO(#58): Restore the rest of the state.

        return true;
    }
    return false;
}

From source file:de.earthlingz.oerszebra.DroidZebra.java

/**
 * Called when the activity is first created.
 *//*w ww  .ja  v a 2s  .c  o m*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initBoard();

    clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

    setContentView(R.layout.spash_layout);
    new ActionBarHelper(this).hide();

    mZebraThread = new ZebraEngine(new AndroidContext(this));
    mZebraThread.setHandler(new DroidZebraHandler(getState(), this, mZebraThread));

    this.settingsProvider = new GlobalSettingsLoader(this);
    this.settingsProvider.setOnChangeListener(this);

    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    Log.i("Intent", type + " " + action);

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type) || "message/rfc822".equals(type)) {
            mZebraThread.setInitialGameState(parser.makeMoveList(intent.getStringExtra(Intent.EXTRA_TEXT)));
        } else {
            Log.e("intent", "unknown intent");
        }
    } else if (savedInstanceState != null && savedInstanceState.containsKey("moves_played_count")
            && savedInstanceState.getInt("moves_played_count") > 0) {
        Log.i("moves_play_count", String.valueOf(savedInstanceState.getInt("moves_played_count")));
        Log.i("moves_played", String.valueOf(savedInstanceState.getInt("moves_played")));
        mZebraThread.setInitialGameState(savedInstanceState.getInt("moves_played_count"),
                savedInstanceState.getByteArray("moves_played"));
    }

    mZebraThread.start();

    newCompletionPort(ZebraEngine.ES_READY2PLAY, () -> {
        DroidZebra.this.setContentView(R.layout.board_layout);
        new ActionBarHelper(DroidZebra.this).show();
        DroidZebra.this.mBoardView = (BoardView) DroidZebra.this.findViewById(R.id.board);
        DroidZebra.this.mStatusView = (StatusView) DroidZebra.this.findViewById(R.id.status_panel);
        DroidZebra.this.mBoardView.setBoardState(getState());
        DroidZebra.this.mBoardView.setOnMakeMoveListener(DroidZebra.this);
        DroidZebra.this.mBoardView.requestFocus();
        DroidZebra.this.initBoard();
        DroidZebra.this.loadSettings();
        DroidZebra.this.mZebraThread.setEngineState(ZebraEngine.ES_PLAY);
        DroidZebra.this.mIsInitCompleted = true;
    });
}

From source file:org.thialfihar.android.apg.ui.EncryptMessageFragment.java

private void encryptStart(final boolean toClipboard) {
    // Send all information needed to service to edit key in other thread
    Intent intent = new Intent(getActivity(), ApgIntentService.class);

    intent.setAction(ApgIntentService.ACTION_ENCRYPT_SIGN);

    // fill values for this action
    Bundle data = new Bundle();

    data.putInt(ApgIntentService.TARGET, ApgIntentService.TARGET_BYTES);

    String message = mMessage.getText().toString();

    if (mEncryptInterface.isModeSymmetric()) {
        Log.d(Constants.TAG, "Symmetric encryption enabled!");
        String passphrase = mEncryptInterface.getPassphrase();
        if (passphrase.length() == 0) {
            passphrase = null;//w w  w .jav a2  s .c om
        }
        data.putString(ApgIntentService.ENCRYPT_SYMMETRIC_PASSPHRASE, passphrase);
    } else {
        data.putLong(ApgIntentService.ENCRYPT_SIGNATURE_KEY_ID, mEncryptInterface.getSignatureKey());
        data.putLongArray(ApgIntentService.ENCRYPT_ENCRYPTION_KEYS_IDS, mEncryptInterface.getEncryptionKeys());

        boolean signOnly = (mEncryptInterface.getEncryptionKeys() == null
                || mEncryptInterface.getEncryptionKeys().length == 0);
        if (signOnly) {
            message = fixBadCharactersForGmail(message);
        }
    }

    data.putByteArray(ApgIntentService.ENCRYPT_MESSAGE_BYTES, message.getBytes());

    data.putBoolean(ApgIntentService.ENCRYPT_USE_ASCII_ARMOR, true);

    int compressionId = Preferences.getPreferences(getActivity()).getDefaultMessageCompression();
    data.putInt(ApgIntentService.ENCRYPT_COMPRESSION_ID, compressionId);

    intent.putExtra(ApgIntentService.EXTRA_DATA, data);

    final Activity activity = getActivity();
    // Message is received after encrypting is done in ApgIntentService
    ApgIntentServiceHandler saveHandler = new ApgIntentServiceHandler(getActivity(),
            getString(R.string.progress_encrypting), ProgressDialog.STYLE_HORIZONTAL) {
        public void handleMessage(Message message) {
            // handle messages by standard ApgIntentServiceHandler first
            super.handleMessage(message);

            if (message.arg1 == ApgIntentServiceHandler.MESSAGE_OKAY) {
                // get returned data bundle
                Bundle data = message.getData();

                String output = new String(data.getByteArray(ApgIntentService.RESULT_BYTES));
                Log.d(Constants.TAG, "output: " + output);

                if (mLegacyMode) {
                    Intent result = new Intent();
                    result.putExtra("encryptedMessage", output);
                    activity.setResult(activity.RESULT_OK, result);
                    activity.finish();
                    return;
                } else if (toClipboard) {
                    ClipboardReflection.copyToClipboard(getActivity(), output);
                    AppMsg.makeText(getActivity(), R.string.encrypt_sign_clipboard_successful,
                            AppMsg.STYLE_INFO).show();
                } else {
                    Intent sendIntent = new Intent(Intent.ACTION_SEND);

                    // Type is set to text/plain so that encrypted messages can
                    // be sent with Whatsapp, Hangouts, SMS etc...
                    sendIntent.setType("text/plain");

                    sendIntent.putExtra(Intent.EXTRA_TEXT, output);
                    startActivity(Intent.createChooser(sendIntent, getString(R.string.title_share_with)));
                }
            }
        }
    };

    // Create a new Messenger for the communication back
    Messenger messenger = new Messenger(saveHandler);
    intent.putExtra(ApgIntentService.EXTRA_MESSENGER, messenger);

    // show progress dialog
    saveHandler.showProgressDialog(getActivity());

    // start service with intent
    getActivity().startService(intent);
}

From source file:org.sufficientlysecure.keychain.ui.EncryptMessageFragment.java

private void encryptStart(final boolean toClipboard) {
    // Send all information needed to service to edit key in other thread
    Intent intent = new Intent(getActivity(), KeychainIntentService.class);

    intent.setAction(KeychainIntentService.ACTION_ENCRYPT_SIGN);

    // fill values for this action
    Bundle data = new Bundle();

    data.putInt(KeychainIntentService.TARGET, KeychainIntentService.TARGET_BYTES);

    String message = mMessage.getText().toString();

    if (mEncryptInterface.isModeSymmetric()) {
        Log.d(Constants.TAG, "Symmetric encryption enabled!");
        String passphrase = mEncryptInterface.getPassphrase();
        if (passphrase.length() == 0) {
            passphrase = null;/*from  ww w. j av  a  2  s .  c  o m*/
        }
        data.putString(KeychainIntentService.ENCRYPT_SYMMETRIC_PASSPHRASE, passphrase);
    } else {
        data.putLong(KeychainIntentService.ENCRYPT_SIGNATURE_KEY_ID, mEncryptInterface.getSignatureKey());
        data.putLongArray(KeychainIntentService.ENCRYPT_ENCRYPTION_KEYS_IDS,
                mEncryptInterface.getEncryptionKeys());

        boolean signOnly = (mEncryptInterface.getEncryptionKeys() == null
                || mEncryptInterface.getEncryptionKeys().length == 0);
        if (signOnly) {
            message = fixBadCharactersForGmail(message);
        }
    }

    data.putByteArray(KeychainIntentService.ENCRYPT_MESSAGE_BYTES, message.getBytes());

    data.putBoolean(KeychainIntentService.ENCRYPT_USE_ASCII_ARMOR, true);

    int compressionId = Preferences.getPreferences(getActivity()).getDefaultMessageCompression();
    data.putInt(KeychainIntentService.ENCRYPT_COMPRESSION_ID, compressionId);

    intent.putExtra(KeychainIntentService.EXTRA_DATA, data);

    // Message is received after encrypting is done in KeychainIntentService
    KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(getActivity(),
            getString(R.string.progress_encrypting), ProgressDialog.STYLE_HORIZONTAL) {
        public void handleMessage(Message message) {
            // handle messages by standard KeychainIntentServiceHandler first
            super.handleMessage(message);

            if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) {
                // get returned data bundle
                Bundle data = message.getData();

                String output = new String(data.getByteArray(KeychainIntentService.RESULT_BYTES));
                Log.d(Constants.TAG, "output: " + output);

                if (toClipboard) {
                    ClipboardReflection.copyToClipboard(getActivity(), output);
                    AppMsg.makeText(getActivity(), R.string.encrypt_sign_clipboard_successful,
                            AppMsg.STYLE_INFO).show();
                } else {
                    Intent sendIntent = new Intent(Intent.ACTION_SEND);

                    // Type is set to text/plain so that encrypted messages can
                    // be sent with Whatsapp, Hangouts, SMS etc...
                    sendIntent.setType("text/plain");

                    sendIntent.putExtra(Intent.EXTRA_TEXT, output);
                    startActivity(Intent.createChooser(sendIntent, getString(R.string.title_share_with)));
                }
            }
        }
    };

    // Create a new Messenger for the communication back
    Messenger messenger = new Messenger(saveHandler);
    intent.putExtra(KeychainIntentService.EXTRA_MESSENGER, messenger);

    // show progress dialog
    saveHandler.showProgressDialog(getActivity());

    // start service with intent
    getActivity().startService(intent);
}

From source file:org.thialfihar.android.apg.ui.EditKeyActivity.java

/**
 * Handle intent action to create new key
 *
 * @param intent//  w w  w.  jav  a  2  s  .c o  m
 */
private void handleActionCreateKey(Intent intent) {
    Bundle extras = intent.getExtras();

    mCurrentPassphrase = "";
    mIsBrandNewKeyring = true;

    if (extras != null) {
        // if userId is given, prefill the fields
        if (extras.containsKey(EXTRA_USER_IDS)) {
            Log.d(Constants.TAG, "UserIds are given!");
            mUserIds.add(extras.getString(EXTRA_USER_IDS));
        }

        // if no passphrase is given
        if (extras.containsKey(EXTRA_NO_PASSPHRASE)) {
            boolean noPassphrase = extras.getBoolean(EXTRA_NO_PASSPHRASE);
            if (noPassphrase) {
                // check "no passphrase" checkbox and remove button
                mNoPassphrase.setChecked(true);
                mChangePassphrase.setVisibility(View.GONE);
            }
        }

        // generate key
        if (extras.containsKey(EXTRA_GENERATE_DEFAULT_KEYS)) {
            boolean generateDefaultKeys = extras.getBoolean(EXTRA_GENERATE_DEFAULT_KEYS);
            if (generateDefaultKeys) {

                // Send all information needed to service generate keys in other thread
                final Intent serviceIntent = new Intent(this, ApgIntentService.class);
                serviceIntent.setAction(ApgIntentService.ACTION_GENERATE_DEFAULT_RSA_KEYS);

                // fill values for this action
                Bundle data = new Bundle();
                data.putString(ApgIntentService.GENERATE_KEY_SYMMETRIC_PASSPHRASE, mCurrentPassphrase);

                serviceIntent.putExtra(ApgIntentService.EXTRA_DATA, data);

                // Message is received after generating is done in ApgIntentService
                ApgIntentServiceHandler saveHandler = new ApgIntentServiceHandler(this,
                        getResources().getQuantityString(R.plurals.progress_generating, 1),
                        ProgressDialog.STYLE_HORIZONTAL, true,

                        new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                // Stop key generation on cancel
                                stopService(serviceIntent);
                                EditKeyActivity.this.setResult(Activity.RESULT_CANCELED);
                                EditKeyActivity.this.finish();
                            }
                        }) {

                    @Override
                    public void handleMessage(Message message) {
                        // handle messages by standard ApgIntentServiceHandler first
                        super.handleMessage(message);

                        if (message.arg1 == ApgIntentServiceHandler.MESSAGE_OKAY) {
                            // get new key from data bundle returned from service
                            Bundle data = message.getData();

                            ArrayList<PGPSecretKey> newKeys = PgpConversionHelper.BytesToPGPSecretKeyList(
                                    data.getByteArray(ApgIntentService.RESULT_NEW_KEY));

                            ArrayList<Integer> keyUsageFlags = data
                                    .getIntegerArrayList(ApgIntentService.RESULT_KEY_USAGES);

                            if (newKeys.size() == keyUsageFlags.size()) {
                                for (int i = 0; i < newKeys.size(); ++i) {
                                    mKeys.add(newKeys.get(i));
                                    mKeysUsages.add(keyUsageFlags.get(i));
                                }
                            }

                            buildLayout(true);
                        }
                    }
                };

                // Create a new Messenger for the communication back
                Messenger messenger = new Messenger(saveHandler);
                serviceIntent.putExtra(ApgIntentService.EXTRA_MESSENGER, messenger);

                saveHandler.showProgressDialog(this);

                // start service with intent
                startService(serviceIntent);
            }
        }
    } else {
        buildLayout(false);
    }
}

From source file:org.sufficientlysecure.keychain.ui.EditKeyActivity.java

/**
 * Handle intent action to create new key
 *
 * @param intent/*from   w  w w.java 2 s.  c o  m*/
 */
private void handleActionCreateKey(Intent intent) {
    Bundle extras = intent.getExtras();

    mCurrentPassphrase = "";
    mIsBrandNewKeyring = true;

    if (extras != null) {
        // if userId is given, prefill the fields
        if (extras.containsKey(EXTRA_USER_IDS)) {
            Log.d(Constants.TAG, "UserIds are given!");
            mUserIds.add(extras.getString(EXTRA_USER_IDS));
        }

        // if no passphrase is given
        if (extras.containsKey(EXTRA_NO_PASSPHRASE)) {
            boolean noPassphrase = extras.getBoolean(EXTRA_NO_PASSPHRASE);
            if (noPassphrase) {
                // check "no passphrase" checkbox and remove button
                mNoPassphrase.setChecked(true);
                mChangePassphrase.setVisibility(View.GONE);
            }
        }

        // generate key
        if (extras.containsKey(EXTRA_GENERATE_DEFAULT_KEYS)) {
            boolean generateDefaultKeys = extras.getBoolean(EXTRA_GENERATE_DEFAULT_KEYS);
            if (generateDefaultKeys) {

                // Send all information needed to service generate keys in other thread
                final Intent serviceIntent = new Intent(this, KeychainIntentService.class);
                serviceIntent.setAction(KeychainIntentService.ACTION_GENERATE_DEFAULT_RSA_KEYS);

                // fill values for this action
                Bundle data = new Bundle();
                data.putString(KeychainIntentService.GENERATE_KEY_SYMMETRIC_PASSPHRASE, mCurrentPassphrase);

                serviceIntent.putExtra(KeychainIntentService.EXTRA_DATA, data);

                // Message is received after generating is done in KeychainIntentService
                KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this,
                        getResources().getQuantityString(R.plurals.progress_generating, 1),
                        ProgressDialog.STYLE_HORIZONTAL, true,

                        new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                // Stop key generation on cancel
                                stopService(serviceIntent);
                                EditKeyActivity.this.setResult(Activity.RESULT_CANCELED);
                                EditKeyActivity.this.finish();
                            }
                        }) {

                    @Override
                    public void handleMessage(Message message) {
                        // handle messages by standard KeychainIntentServiceHandler first
                        super.handleMessage(message);

                        if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) {
                            // get new key from data bundle returned from service
                            Bundle data = message.getData();

                            ArrayList<UncachedSecretKey> newKeys = PgpConversionHelper.BytesToPGPSecretKeyList(
                                    data.getByteArray(KeychainIntentService.RESULT_NEW_KEY));

                            ArrayList<Integer> keyUsageFlags = data
                                    .getIntegerArrayList(KeychainIntentService.RESULT_KEY_USAGES);

                            if (newKeys.size() == keyUsageFlags.size()) {
                                for (int i = 0; i < newKeys.size(); ++i) {
                                    mKeys.add(newKeys.get(i));
                                    mKeysUsages.add(keyUsageFlags.get(i));
                                }
                            }

                            buildLayout(true);
                        }
                    }
                };

                // Create a new Messenger for the communication back
                Messenger messenger = new Messenger(saveHandler);
                serviceIntent.putExtra(KeychainIntentService.EXTRA_MESSENGER, messenger);

                saveHandler.showProgressDialog(this);

                // start service with intent
                startService(serviceIntent);
            }
        }
    } else {
        buildLayout(false);
    }
}

From source file:com.zld.ui.ZldNewActivity.java

/**
 * ?? : 2015314 ?:/*from ww  w .ja  va 2s .  c om*/
 *
 * @param bundle ?
 * @throws IOException
 */
private void showHomeInfo(Bundle bundle) throws IOException {
    int height = bundle.getInt("carPlateheight");
    int width = bundle.getInt("carPlatewidth");
    int x = bundle.getInt("xCoordinate");
    int y = bundle.getInt("yCoordinate");
    String carPlate = bundle.getString("carPlate");
    /*int billingType = bundle.getInt("billingType");// ?,
    int nType = bundle.getInt("nType");
    int resType = bundle.getInt("resType");*/
    byte[] byteArray = bundle.getByteArray("bitmap");
    String ledContent = bundle.getString("led_content");
    String cameraIp = bundle.getString("cameraIp");
    long time = System.currentTimeMillis();
    Log.e(TAG, "??" + carPlate + " " + time);
    SharedPreferencesUtils.setParam(getApplicationContext(), "zld_config", "carPlate", carPlate);
    SharedPreferencesUtils.setParam(getApplicationContext(), "zld_config", "current_time", time);
    /* ??ip??ledip?,?ledip??ledinfo,??? */
    if (selectIpIn == null || selectIpIn.size() == 0) {
        showToast("???LED???");
    } else {
        homeledinfo = selectIpIn.get(cameraIp);
        Timer timer = new Timer();//Timer
        timer.schedule(new TimerTask() {
            public void run() {
                socketUtil.sendLedData(null, homeledinfo.getLedip(), null, null, false);
                this.cancel();
            }
        }, 200);//

        if (ledContent != null) {
            if (homeledinfo != null) {
                String passtype = homeledinfo.getPasstype();
                if (passtype.equals(Constant.sZero)) {
                    Log.e(TAG, "homeledinfo:" + homeledinfo);
                    comeIntime = System.currentTimeMillis();
                    if (null != homeledinfo.getLeduid() && homeledinfo.getLeduid().equals("41")) {
                        socketUtil.sendLedData(homeledinfo, "42", ledContent, "", true);
                    } else {
                        socketUtil.sendLedData(homeledinfo, "190351508", ledContent, "", true);
                    }
                    //**
                    //         PollingUtils.startPollingService(this, 0, 1, ShareUiService.class,
                    //               "com.zld.service.ShareUi_Temp");
                }
            }
        }
    }
    Bitmap homeBitmap = ImageUitls.byteBitmap(byteArray);
    homeBitmap = BitmapUtil.zoomImg(homeBitmap, 1280, 720);

    entranceFragment.refreshView(homeBitmap);
    setDetailInCarState(ComeInCarState.ENTRANCE_COME_IN_CAR_STATE);

    if (listFragment != null) {
        Log.e("OrderListState",
                "?????" + OrderListState.getInstance().getState());
        if (OrderListState.getInstance().isOrderFinishState()) {//????
            if (x + width <= homeBitmap.getWidth() && y + height <= homeBitmap.getHeight()) {
                if (x < 10 && y < 10 && width < 10 && height < 10) {
                    detailsFragment.refreshCarPlate(null);
                } else {
                    Log.e(TAG, "???");
                    if (x > 0 && y > 0 && width > 0 && height > 0) {
                        Bitmap smallCarPlateBmp = Bitmap.createBitmap(homeBitmap, x, y, width, height);
                        detailsFragment.refreshCarPlate(smallCarPlateBmp);
                    }
                }
            } else {
                detailsFragment.refreshCarPlate(null);
            }
        }
    }
}