@Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case REQUEST_CODE_PUBLIC_KEYS:
        {
          if (resultCode == Activity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            setEncryptionKeyIds(
                bundle.getLongArray(SelectPublicKeyActivity.RESULT_EXTRA_MASTER_KEY_IDS));
          }
          break;
        }

      case REQUEST_CODE_SECRET_KEYS:
        {
          if (resultCode == Activity.RESULT_OK) {
            Uri uriMasterKey = data.getData();
            setSignatureKeyId(Long.valueOf(uriMasterKey.getLastPathSegment()));
          } else {
            setSignatureKeyId(Constants.key.none);
          }
          break;
        }

      default:
        {
          super.onActivityResult(requestCode, resultCode, data);

          break;
        }
    }
  }
Example #2
0
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.confirm_delete);
    getWindow()
        .setLayout(WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

    mPrompt = (TextView) findViewById(R.id.prompt);
    mButton = (Button) findViewById(R.id.delete);
    mButton.setOnClickListener(mButtonClicked);

    ((Button) findViewById(R.id.cancel))
        .setOnClickListener(
            new View.OnClickListener() {
              public void onClick(View v) {
                finish();
              }
            });

    Bundle b = getIntent().getExtras();
    String desc = b.getString("description");
    mItemList = b.getLongArray("items");

    mPrompt.setText(desc);
  }
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.select_categories);
    setTitle(getResources().getString(R.string.select_categories));

    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);

    lv = getListView();
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    lv.setItemsCanFocus(false);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      id = extras.getInt("id");
      try {
        blog = new Blog(id);
      } catch (Exception e) {
        Toast.makeText(this, getResources().getText(R.string.blog_not_found), Toast.LENGTH_SHORT)
            .show();
        finish();
      }
      checkedCategories = extras.getLongArray("checkedCategories");
      categoriesCSV = extras.getString("categoriesCSV");
    }

    loadCategories();
  }
 @Override
 protected void onRestoreInstanceState(Bundle savedInstanceState) {
   super.onRestoreInstanceState(savedInstanceState);
   long[] selectedArray = savedInstanceState.getLongArray(BUNDLE_SELECTED_ITEMS_KEY);
   for (int i = 0; i < selectedArray.length; i++) mSelected.add(selectedArray[i]);
   mToggled = savedInstanceState.getBoolean(BUNDLE_TOGGLED_KEY);
   mRestored = true;
   mUploadButton.setEnabled(selectedArray.length > 0);
   mSMSButton.setEnabled(selectedArray.length > 0);
 }
 @Override
 protected void onRestoreInstanceState(Bundle savedInstanceState) {
   super.onRestoreInstanceState(savedInstanceState);
   mIsSortedBySize = savedInstanceState.getBoolean("isSortedBySize");
   mSelectedIds.clear();
   for (long selectedId : savedInstanceState.getLongArray("selection")) {
     mSelectedIds.add(selectedId);
   }
   chooseListToShow();
   showOrHideSelectionMenu();
 }
  @Override
  protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    long[] state = savedInstanceState.getLongArray(OUTLINE_NODES);
    if (state != null) listView.setState(state);

    int checkedPos = savedInstanceState.getInt(OUTLINE_CHECKED_POS, 0);
    listView.setItemChecked(checkedPos, true);

    int scrollPos = savedInstanceState.getInt(OUTLINE_SCROLL_POS, 0);
    listView.setSelection(scrollPos);
  }
  @Override
  public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (savedInstanceState != null) {
      ArrayList<SocialMember> friends =
          savedInstanceState.getParcelableArrayList(FRIEND_LIST_MODELS);

      friendListAdapter.setItems(friends);

      // Restore the saved selected set
      long[] selected = savedInstanceState.getLongArray(FRIEND_LIST_STATES);
      if (selected != null) {
        friendListAdapter.setSelectedList(JavaUtil.primitiveLongToSet(selected));
      }
      // Restore the saved already in group set
      long[] alreadyInGroup = savedInstanceState.getLongArray(FRIEND_LIST_ALREADY_IN_GROUP);
      if (alreadyInGroup != null) {
        friendListAdapter.setAlreadyInGroupList(JavaUtil.primitiveLongToSet(alreadyInGroup));
      }
      refreshPage(State.LOADED);
    } else if (getArguments() != null && getArguments().containsKey(EXTRA_OPT_FRIENDS_LIST)) {
      List<SocialMember> friends = getArguments().getParcelableArrayList(EXTRA_OPT_FRIENDS_LIST);
      friendListAdapter.setItems(friends);
      refreshPage(State.LOADED);
    } else {
      friendProvider.getMyFriends(getActivity(), this);
      refreshPage(State.LOADING);
    }

    // Retrieve the already in group list
    if (getArguments() != null && getArguments().containsKey(EXTRA_OPT_IN_GROUP)) {

      long[] alreadyInGroup = getArguments().getLongArray(EXTRA_OPT_IN_GROUP);
      friendListAdapter.setAlreadyInGroupList(JavaUtil.primitiveLongToSet(alreadyInGroup));
    }
  }
Example #8
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_entry, container, false);

    mCancelFullscreenBtn = rootView.findViewById(R.id.cancelFullscreenBtn);
    mCancelFullscreenBtn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            toggleFullScreen();
          }
        });

    mEntryPager = (ViewPager) rootView.findViewById(R.id.pager);
    // mEntryPager.setPageTransformer(true, new DepthPageTransformer());
    mEntryPager.setAdapter(mEntryPagerAdapter);

    if (savedInstanceState != null) {
      mBaseUri = savedInstanceState.getParcelable(STATE_BASE_URI);
      mEntriesIds = savedInstanceState.getLongArray(STATE_ENTRIES_IDS);
      mInitialEntryId = savedInstanceState.getLong(STATE_INITIAL_ENTRY_ID);
      mCurrentPagerPos = savedInstanceState.getInt(STATE_CURRENT_PAGER_POS);
      mEntryPager.getAdapter().notifyDataSetChanged();
      mEntryPager.setCurrentItem(mCurrentPagerPos);
      mEntryPagerAdapter.setScrollPercentage(savedInstanceState.getFloat(STATE_SCROLL_PERCENTAGE));
    }

    mEntryPager.setOnPageChangeListener(
        new ViewPager.OnPageChangeListener() {
          @Override
          public void onPageScrolled(int i, float v, int i2) {}

          @Override
          public void onPageSelected(int i) {
            mCurrentPagerPos = i;
            mEntryPagerAdapter.onPause(); // pause all webviews
            mEntryPagerAdapter.onResume(); // resume the current webview

            refreshUI(mEntryPagerAdapter.getCursor(i));
          }

          @Override
          public void onPageScrollStateChanged(int i) {}
        });

    return rootView;
  }
Example #9
0
 public void load(Bundle bundle) {
   lastMoveTime = System.currentTimeMillis();
   cost = 0;
   if (bundle == null) return;
   int x[] = bundle.getIntArray("x");
   int y[] = bundle.getIntArray("y");
   long[] d = bundle.getLongArray("d");
   cost = bundle.getLong("cost", 0);
   if (x == null || y == null || d == null) return;
   for (int n = 0; n < x.length; n++) {
     Item item = new Item();
     item.x = x[n];
     item.y = y[n];
     item.duration = d[n];
     cost += d[n];
     items.add(item);
   }
 }
  @Override
  public void restoreState(Parcelable state, ClassLoader loader) {
    if (state != null) {
      Bundle bundle = (Bundle) state;
      bundle.setClassLoader(loader);

      mItemIds = bundle.getLongArray("itemids");
      if (mItemIds == null) {
        mItemIds = new long[] {};
      }

      Parcelable[] fss = bundle.getParcelableArray("states");
      mSavedState.clear();
      mFragments.clear();
      if (fss != null) {
        for (int i = 0; i < fss.length; i++) {
          mSavedState.add((Fragment.SavedState) fss[i]);
        }
      }
      Iterable<String> keys = bundle.keySet();
      for (String key : keys) {
        if (key.startsWith("f")) {
          int index = Integer.parseInt(key.substring(1));
          try {
            Fragment f = mFragmentManager.getFragment(bundle, key);
            if (f != null) {
              while (mFragments.size() <= index) {
                mFragments.add(null);
              }
              f.setMenuVisibility(false);
              mFragments.set(index, f);
            } else {
              Log.w(TAG, "Bad fragment at key " + key);
            }
          } catch (Exception ex) {
            Log.w(TAG, "Cannot restore fragment " + key, ex);
          }
        }
      }
      checkForIdChanges();
    }
  }
Example #11
0
 /**
  * Check if the state can be restored. If the state can be restored, the current tab id is
  * returned. This can be passed to restoreState below in order to restore the correct tab.
  * Otherwise, -1 is returned and the state cannot be restored.
  */
 long canRestoreState(Bundle inState, boolean restoreIncognitoTabs) {
   final long[] ids = (inState == null) ? null : inState.getLongArray(POSITIONS);
   if (ids == null) {
     return -1;
   }
   final long oldcurrent = inState.getLong(CURRENT);
   long current = -1;
   if (restoreIncognitoTabs
       || (hasState(oldcurrent, inState) && !isIncognito(oldcurrent, inState))) {
     current = oldcurrent;
   } else {
     // pick first non incognito tab
     for (long id : ids) {
       if (hasState(id, inState) && !isIncognito(id, inState)) {
         current = id;
         break;
       }
     }
   }
   return current;
 }
    @Override
    protected Bundle doInBackground(Bundle... params) {
      Bundle args = params[0];
      Bundle result = new Bundle();
      long[] userIDs;
      userIDs = args.getLongArray(PARAM_USER_ID);

      try {
        List<User> users = mTwitter.lookupUsers(userIDs);
        ArrayList<SocialPerson> socialUsers = new ArrayList<SocialPerson>();
        SocialPerson socialUser = new SocialPerson();
        for (User user : users) {
          getSocialPerson(socialUser, user);
          socialUsers.add(socialUser);
          socialUser = new SocialPerson();
        }
        result.putParcelableArrayList(RESULT_USERS_ARRAY, socialUsers);
      } catch (TwitterException e) {
        result.putString(RESULT_ERROR, e.getMessage());
      }
      return result;
    }
  /**
   * The IntentService calls this method from the default worker thread with the intent that started
   * the service. When this method returns, IntentService stops the service, as appropriate.
   */
  @Override
  protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    if (extras == null) {
      Log.e(Constants.TAG, "Extras bundle is null!");
      return;
    }

    if (!(extras.containsKey(EXTRA_MESSENGER)
        || extras.containsKey(EXTRA_DATA)
        || (intent.getAction() == null))) {
      Log.e(Constants.TAG, "Extra bundle must contain a messenger, a data bundle, and an action!");
      return;
    }

    Uri dataUri = intent.getData();

    mMessenger = (Messenger) extras.get(EXTRA_MESSENGER);
    Bundle data = extras.getBundle(EXTRA_DATA);

    OtherHelper.logDebugBundle(data, "EXTRA_DATA");

    String action = intent.getAction();

    // executeServiceMethod action from extra bundle
    if (ACTION_ENCRYPT_SIGN.equals(action)
        || "org.thialfihar.android.apg.intent.ENCRYPT_AND_RETURN".equals(action)) {
      try {
        /* Input */
        int target = data.getInt(TARGET);

        long signatureKeyId = data.getLong(ENCRYPT_SIGNATURE_KEY_ID);
        String symmetricPassphrase = data.getString(ENCRYPT_SYMMETRIC_PASSPHRASE);

        boolean useAsciiArmor = data.getBoolean(ENCRYPT_USE_ASCII_ARMOR);
        long encryptionKeyIds[] = data.getLongArray(ENCRYPT_ENCRYPTION_KEYS_IDS);
        int compressionId = data.getInt(ENCRYPT_COMPRESSION_ID);
        boolean generateSignature = data.getBoolean(ENCRYPT_GENERATE_SIGNATURE);
        InputStream inStream;
        long inLength;
        InputData inputData;
        OutputStream outStream;
        //                String streamFilename = null;
        switch (target) {
          case TARGET_BYTES: /* encrypting bytes directly */
            byte[] bytes = data.getByteArray(ENCRYPT_MESSAGE_BYTES);

            inStream = new ByteArrayInputStream(bytes);
            inLength = bytes.length;

            inputData = new InputData(inStream, inLength);
            outStream = new ByteArrayOutputStream();

            break;
          case TARGET_URI: /* encrypting file */
            String inputFile = data.getString(ENCRYPT_INPUT_FILE);
            String outputFile = data.getString(ENCRYPT_OUTPUT_FILE);

            // check if storage is ready
            if (!FileHelper.isStorageMounted(inputFile)
                || !FileHelper.isStorageMounted(outputFile)) {
              throw new PgpGeneralException(getString(R.string.error_external_storage_not_ready));
            }

            inStream = new FileInputStream(inputFile);
            File file = new File(inputFile);
            inLength = file.length();
            inputData = new InputData(inStream, inLength);

            outStream = new FileOutputStream(outputFile);

            break;

            // TODO: not used currently
            //                    case TARGET_STREAM: /* Encrypting stream from content uri */
            //                        Uri providerUri = (Uri)
            // data.getParcelable(ENCRYPT_PROVIDER_URI);
            //
            //                        // InputStream
            //                        InputStream in =
            // getContentResolver().openInputStream(providerUri);
            //                        inLength = PgpHelper.getLengthOfStream(in);
            //                        inputData = new InputData(in, inLength);
            //
            //                        // OutputStream
            //                        try {
            //                            while (true) {
            //                                streamFilename = PgpHelper.generateRandomFilename(32);
            //                                if (streamFilename == null) {
            //                                    throw new PgpGeneralException("couldn't generate
            // random file name");
            //                                }
            //                                openFileInput(streamFilename).close();
            //                            }
            //                        } catch (FileNotFoundException e) {
            //                            // found a name that isn't used yet
            //                        }
            //                        outStream = openFileOutput(streamFilename,
            // Context.MODE_PRIVATE);
            //
            //                        break;

          default:
            throw new PgpGeneralException("No target choosen!");
        }

        /* Operation */
        PgpSignEncrypt.Builder builder =
            new PgpSignEncrypt.Builder(this, inputData, outStream, new ProviderHelper(this));
        builder.setProgressable(this);

        if (generateSignature) {
          Log.d(Constants.TAG, "generating signature...");
          builder
              .setEnableAsciiArmorOutput(useAsciiArmor)
              .setSignatureForceV3(Preferences.getPreferences(this).getForceV3Signatures())
              .setSignatureKeyId(signatureKeyId)
              .setSignatureHashAlgorithm(Preferences.getPreferences(this).getDefaultHashAlgorithm())
              .setSignaturePassphrase(
                  PassphraseCacheService.getCachedPassphrase(this, signatureKeyId));

          builder.build().generateSignature();
        } else {
          Log.d(Constants.TAG, "encrypt...");
          builder
              .setEnableAsciiArmorOutput(useAsciiArmor)
              .setCompressionId(compressionId)
              .setSymmetricEncryptionAlgorithm(
                  Preferences.getPreferences(this).getDefaultEncryptionAlgorithm())
              .setSignatureForceV3(Preferences.getPreferences(this).getForceV3Signatures())
              .setEncryptionKeyIds(encryptionKeyIds)
              .setSymmetricPassphrase(symmetricPassphrase)
              .setSignatureKeyId(signatureKeyId)
              .setSignatureHashAlgorithm(Preferences.getPreferences(this).getDefaultHashAlgorithm())
              .setSignaturePassphrase(
                  PassphraseCacheService.getCachedPassphrase(this, signatureKeyId));

          builder.build().execute();
        }

        outStream.close();

        /* Output */

        Bundle resultData = new Bundle();

        switch (target) {
          case TARGET_BYTES:
            byte output[] = ((ByteArrayOutputStream) outStream).toByteArray();

            resultData.putByteArray(RESULT_BYTES, output);

            break;
          case TARGET_URI:
            // nothing, file was written, just send okay

            break;
            //                    case TARGET_STREAM:
            //                        String uri =
            // DataStream.buildDataStreamUri(streamFilename).toString();
            //                        resultData.putString(RESULT_URI, uri);
            //
            //                        break;
        }

        OtherHelper.logDebugBundle(resultData, "resultData");

        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY, resultData);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_DECRYPT_VERIFY.equals(action)) {
      try {
        /* Input */
        int target = data.getInt(TARGET);

        byte[] bytes = data.getByteArray(DECRYPT_CIPHERTEXT_BYTES);
        String passphrase = data.getString(DECRYPT_PASSPHRASE);

        InputStream inStream;
        long inLength;
        InputData inputData;
        OutputStream outStream;
        String streamFilename = null;
        switch (target) {
          case TARGET_BYTES: /* decrypting bytes directly */
            inStream = new ByteArrayInputStream(bytes);
            inLength = bytes.length;

            inputData = new InputData(inStream, inLength);
            outStream = new ByteArrayOutputStream();

            break;

          case TARGET_URI: /* decrypting file */
            String inputFile = data.getString(ENCRYPT_INPUT_FILE);
            String outputFile = data.getString(ENCRYPT_OUTPUT_FILE);

            // check if storage is ready
            if (!FileHelper.isStorageMounted(inputFile)
                || !FileHelper.isStorageMounted(outputFile)) {
              throw new PgpGeneralException(getString(R.string.error_external_storage_not_ready));
            }

            // InputStream
            inLength = -1;
            inStream = new FileInputStream(inputFile);
            File file = new File(inputFile);
            inLength = file.length();
            inputData = new InputData(inStream, inLength);

            // OutputStream
            outStream = new FileOutputStream(outputFile);

            break;

            // TODO: not used, maybe contains code useful for new decrypt method for files?
            //                    case TARGET_STREAM: /* decrypting stream from content uri */
            //                        Uri providerUri = (Uri)
            // data.getParcelable(ENCRYPT_PROVIDER_URI);
            //
            //                        // InputStream
            //                        InputStream in =
            // getContentResolver().openInputStream(providerUri);
            //                        inLength = PgpHelper.getLengthOfStream(in);
            //                        inputData = new InputData(in, inLength);
            //
            //                        // OutputStream
            //                        try {
            //                            while (true) {
            //                                streamFilename = PgpHelper.generateRandomFilename(32);
            //                                if (streamFilename == null) {
            //                                    throw new PgpGeneralException("couldn't generate
            // random file name");
            //                                }
            //                                openFileInput(streamFilename).close();
            //                            }
            //                        } catch (FileNotFoundException e) {
            //                            // found a name that isn't used yet
            //                        }
            //                        outStream = openFileOutput(streamFilename,
            // Context.MODE_PRIVATE);
            //
            //                        break;

          default:
            throw new PgpGeneralException("No target choosen!");
        }

        /* Operation */

        Bundle resultData = new Bundle();

        // verifyText and decrypt returning additional resultData values for the
        // verification of signatures
        PgpDecryptVerify.Builder builder =
            new PgpDecryptVerify.Builder(this, inputData, outStream, new ProviderHelper(this));
        builder.setProgressable(this);

        builder.setAllowSymmetricDecryption(true).setPassphrase(passphrase);

        PgpDecryptVerifyResult decryptVerifyResult = builder.build().execute();

        outStream.close();

        resultData.putParcelable(RESULT_DECRYPT_VERIFY_RESULT, decryptVerifyResult);

        /* Output */

        switch (target) {
          case TARGET_BYTES:
            byte output[] = ((ByteArrayOutputStream) outStream).toByteArray();
            resultData.putByteArray(RESULT_DECRYPTED_BYTES, output);
            break;
          case TARGET_URI:
            // nothing, file was written, just send okay and verification bundle

            break;
            //                    case TARGET_STREAM:
            //                        String uri =
            // DataStream.buildDataStreamUri(streamFilename).toString();
            //                        resultData.putString(RESULT_URI, uri);
            //
            //                        break;
        }

        OtherHelper.logDebugBundle(resultData, "resultData");

        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY, resultData);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_SAVE_KEYRING.equals(action)) {
      try {
        /* Input */
        SaveKeyringParcel saveParams = data.getParcelable(SAVE_KEYRING_PARCEL);
        String oldPassphrase = saveParams.oldPassphrase;
        String newPassphrase = saveParams.newPassphrase;
        boolean canSign = true;

        if (data.containsKey(SAVE_KEYRING_CAN_SIGN)) {
          canSign = data.getBoolean(SAVE_KEYRING_CAN_SIGN);
        }

        if (newPassphrase == null) {
          newPassphrase = oldPassphrase;
        }

        long masterKeyId = saveParams.keys.get(0).getKeyId();

        /* Operation */
        if (!canSign) {
          PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 0, 50, 100));
          PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRingByKeyId(this, masterKeyId);
          keyRing = keyOperations.changeSecretKeyPassphrase(keyRing, oldPassphrase, newPassphrase);
          setProgress(R.string.progress_saving_key_ring, 50, 100);
          ProviderHelper.saveKeyRing(this, keyRing);
          setProgress(R.string.progress_done, 100, 100);
        } else {
          PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 0, 90, 100));
          PGPSecretKeyRing privkey =
              ProviderHelper.getPGPSecretKeyRingByMasterKeyId(this, masterKeyId);
          PGPPublicKeyRing pubkey =
              ProviderHelper.getPGPPublicKeyRingByMasterKeyId(this, masterKeyId);
          PgpKeyOperation.Pair<PGPSecretKeyRing, PGPPublicKeyRing> pair =
              keyOperations.buildSecretKey(privkey, pubkey, saveParams);
          setProgress(R.string.progress_saving_key_ring, 90, 100);
          ProviderHelper.saveKeyRing(this, pair.first);
          ProviderHelper.saveKeyRing(this, pair.second);
          setProgress(R.string.progress_done, 100, 100);
        }
        PassphraseCacheService.addCachedPassphrase(this, masterKeyId, newPassphrase);

        /* Output */
        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_GENERATE_KEY.equals(action)) {
      try {
        /* Input */
        int algorithm = data.getInt(GENERATE_KEY_ALGORITHM);
        String passphrase = data.getString(GENERATE_KEY_SYMMETRIC_PASSPHRASE);
        int keysize = data.getInt(GENERATE_KEY_KEY_SIZE);
        boolean masterKey = data.getBoolean(GENERATE_KEY_MASTER_KEY);

        /* Operation */
        PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 0, 100, 100));
        Key newKey = keyOperations.createKey(algorithm, keysize, passphrase, masterKey);

        /* Output */
        Bundle resultData = new Bundle();
        resultData.putSerializable(RESULT_NEW_KEY, newKey);

        OtherHelper.logDebugBundle(resultData, "resultData");

        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY, resultData);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_GENERATE_DEFAULT_RSA_KEYS.equals(action)) {
      // generate one RSA 4096 key for signing and one subkey for encrypting!
      try {
        /* Input */
        String passphrase = data.getString(GENERATE_KEY_SYMMETRIC_PASSPHRASE);
        ArrayList<Key> newKeys = new ArrayList<Key>();
        ArrayList<Integer> keyUsageList = new ArrayList<Integer>();

        /* Operation */
        int keysTotal = 3;
        int keysCreated = 0;
        setProgress(
            getApplicationContext()
                .getResources()
                .getQuantityString(R.plurals.progress_generating, keysTotal),
            keysCreated,
            keysTotal);
        PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 0, 100, 100));

        Key masterKey = keyOperations.createKey(Id.choice.algorithm.rsa, 4096, passphrase, true);
        newKeys.add(masterKey);
        keyUsageList.add(KeyFlags.CERTIFY_OTHER);
        keysCreated++;
        setProgress(keysCreated, keysTotal);

        Key subKey = keyOperations.createKey(Id.choice.algorithm.rsa, 4096, passphrase, false);
        newKeys.add(subKey);
        keyUsageList.add(KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE);
        keysCreated++;
        setProgress(keysCreated, keysTotal);

        subKey = keyOperations.createKey(Id.choice.algorithm.rsa, 4096, passphrase, false);
        newKeys.add(subKey);
        keyUsageList.add(KeyFlags.SIGN_DATA);
        keysCreated++;
        setProgress(keysCreated, keysTotal);

        // TODO: default to one master for cert, one sub for encrypt and one sub
        //       for sign

        /* Output */

        Bundle resultData = new Bundle();
        resultData.putSerializable(RESULT_NEW_KEY, newKeys);
        resultData.putIntegerArrayList(RESULT_KEY_USAGES, keyUsageList);

        OtherHelper.logDebugBundle(resultData, "resultData");

        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY, resultData);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_DELETE_FILE_SECURELY.equals(action)) {
      try {
        /* Input */
        String deleteFile = data.getString(DELETE_FILE);

        /* Operation */
        try {
          PgpHelper.deleteFileSecurely(this, this, new File(deleteFile));
        } catch (FileNotFoundException e) {
          throw new PgpGeneralException(getString(R.string.error_file_not_found, deleteFile));
        } catch (IOException e) {
          throw new PgpGeneralException(getString(R.string.error_file_delete_failed, deleteFile));
        }

        /* Output */
        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_IMPORT_KEYRING.equals(action)) {
      try {
        List<ImportKeysListEntry> entries = data.getParcelableArrayList(IMPORT_KEY_LIST);

        Bundle resultData = new Bundle();

        PgpImportExport pgpImportExport = new PgpImportExport(this, this);
        resultData = pgpImportExport.importKeyRings(entries);

        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY, resultData);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_EXPORT_KEYRING.equals(action)) {
      try {

        /* Input */
        int keyType = Id.type.public_key;
        if (data.containsKey(EXPORT_KEY_TYPE)) {
          keyType = data.getInt(EXPORT_KEY_TYPE);
        }
        long[] masterKeyIds = data.getLongArray(EXPORT_KEY_RING_MASTER_KEY_ID);
        String outputFile = data.getString(EXPORT_FILENAME);

        // If not exporting all keys get the masterKeyIds of the keys to export from the intent
        boolean exportAll = data.getBoolean(EXPORT_ALL);

        /* Operation */

        // check if storage is ready
        if (!FileHelper.isStorageMounted(outputFile)) {
          throw new PgpGeneralException(getString(R.string.error_external_storage_not_ready));
        }

        ArrayList<Long> publicMasterKeyIds = new ArrayList<Long>();
        ArrayList<Long> secretMasterKeyIds = new ArrayList<Long>();
        ArrayList<Long> allPublicMasterKeyIds = ProviderHelper.getPublicKeyRingsMasterKeyIds(this);
        ArrayList<Long> allSecretMasterKeyIds = ProviderHelper.getSecretKeyRingsMasterKeyIds(this);

        if (exportAll) {
          // get all public key ring MasterKey ids
          if (keyType == Id.type.public_key || keyType == Id.type.public_secret_key) {
            publicMasterKeyIds = allPublicMasterKeyIds;
          }
          // get all secret key ring MasterKey ids
          if (keyType == Id.type.secret_key || keyType == Id.type.public_secret_key) {
            secretMasterKeyIds = allSecretMasterKeyIds;
          }
        } else {

          for (long masterKeyId : masterKeyIds) {
            if ((keyType == Id.type.public_key || keyType == Id.type.public_secret_key)
                && allPublicMasterKeyIds.contains(masterKeyId)) {
              publicMasterKeyIds.add(masterKeyId);
            }
            if ((keyType == Id.type.secret_key || keyType == Id.type.public_secret_key)
                && allSecretMasterKeyIds.contains(masterKeyId)) {
              secretMasterKeyIds.add(masterKeyId);
            }
          }
        }

        PgpImportExport pgpImportExport = new PgpImportExport(this, this, this);

        Bundle resultData =
            pgpImportExport.exportKeyRings(
                publicMasterKeyIds, secretMasterKeyIds, new FileOutputStream(outputFile));

        if (mIsCanceled) {
          new File(outputFile).delete();
        }

        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY, resultData);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_UPLOAD_KEYRING.equals(action)) {
      try {

        /* Input */
        String keyServer = data.getString(UPLOAD_KEY_SERVER);
        // and dataUri!

        /* Operation */
        HkpKeyServer server = new HkpKeyServer(keyServer);

        KeyRing keyRing = ProviderHelper.getKeyRing(this, dataUri);
        if (keyRing != null) {
          PgpImportExport pgpImportExport = new PgpImportExport(this, null);

          boolean uploaded =
              pgpImportExport.uploadKeyRingToServer(server, new PublicKeyRing(keyRing));
          if (!uploaded) {
            throw new PgpGeneralException("Unable to export key to selected server");
          }
        }

        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_DOWNLOAD_AND_IMPORT_KEYS.equals(action)) {
      try {
        ArrayList<ImportKeysListEntry> entries = data.getParcelableArrayList(DOWNLOAD_KEY_LIST);
        String keyServer = data.getString(DOWNLOAD_KEY_SERVER);

        // TODO: add extra which requires fingerprint suport and force verification!
        // only supported by newer sks keyserver versions

        // this downloads the keys and places them into the ImportKeysListEntry entries
        HkpKeyServer server = new HkpKeyServer(keyServer);

        for (ImportKeysListEntry entry : entries) {
          // if available use complete fingerprint for get request
          byte[] downloadedKeyBytes;
          if (entry.getFingerPrintHex() != null) {
            downloadedKeyBytes = server.get("0x" + entry.getFingerPrintHex()).getBytes();
          } else {
            downloadedKeyBytes = server.get(entry.getKeyIdHex()).getBytes();
          }

          // create PGPKeyRing object based on downloaded armored key
          PGPKeyRing downloadedKey = null;
          BufferedInputStream bufferedInput =
              new BufferedInputStream(new ByteArrayInputStream(downloadedKeyBytes));
          if (bufferedInput.available() > 0) {
            InputStream in = PGPUtil.getDecoderStream(bufferedInput);
            PGPObjectFactory objectFactory = new PGPObjectFactory(in);

            // get first object in block
            Object obj;
            if ((obj = objectFactory.nextObject()) != null) {
              Log.d(Constants.TAG, "Found class: " + obj.getClass());

              if (obj instanceof PGPKeyRing) {
                downloadedKey = (PGPKeyRing) obj;
              } else {
                throw new PgpGeneralException("Object not recognized as PGPKeyRing!");
              }
            }
          }

          // verify downloaded key by comparing fingerprints
          if (entry.getFingerPrintHex() != null) {
            String downloadedKeyFp =
                PgpKeyHelper.convertFingerprintToHex(downloadedKey.getPublicKey().getFingerprint());
            if (downloadedKeyFp.equals(entry.getFingerPrintHex())) {
              Log.d(
                  Constants.TAG,
                  "fingerprint of downloaded key is the same as " + "the requested fingerprint!");
            } else {
              throw new PgpGeneralException(
                  "fingerprint of downloaded key is "
                      + "NOT the same as the requested fingerprint!");
            }
          }

          // save key bytes in entry object for doing the
          // actual import afterwards
          entry.setBytes(downloadedKey.getEncoded());
        }

        Intent importIntent = new Intent(this, ApgIntentService.class);

        importIntent.setAction(ACTION_IMPORT_KEYRING);
        Bundle importData = new Bundle();
        importData.putParcelableArrayList(IMPORT_KEY_LIST, entries);
        importIntent.putExtra(EXTRA_DATA, importData);
        importIntent.putExtra(EXTRA_MESSENGER, mMessenger);

        // now import it with this service
        onHandleIntent(importIntent);

        // result is handled in ACTION_IMPORT_KEYRING
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    } else if (ACTION_CERTIFY_KEYRING.equals(action)) {
      try {

        /* Input */
        long masterKeyId = data.getLong(CERTIFY_KEY_MASTER_KEY_ID);
        long pubKeyId = data.getLong(CERTIFY_KEY_PUB_KEY_ID);
        ArrayList<String> userIds = data.getStringArrayList(CERTIFY_KEY_UIDS);

        /* Operation */
        String signaturePassphrase = PassphraseCacheService.getCachedPassphrase(this, masterKeyId);
        if (signaturePassphrase == null) {
          throw new PgpGeneralException("Unable to obtain passphrase");
        }

        PgpKeyOperation keyOperation = new PgpKeyOperation(new ProgressScaler(this, 0, 100, 100));
        PGPPublicKeyRing publicRing = ProviderHelper.getPGPPublicKeyRingByKeyId(this, pubKeyId);
        PGPPublicKey publicKey = publicRing.getPublicKey(pubKeyId);
        PGPSecretKey certificationKey = PgpKeyHelper.getCertificationKey(this, masterKeyId);
        publicKey =
            keyOperation.certifyKey(certificationKey, publicKey, userIds, signaturePassphrase);
        publicRing = PGPPublicKeyRing.insertPublicKey(publicRing, publicKey);

        // store the signed key in our local cache
        PgpImportExport pgpImportExport = new PgpImportExport(this, null);
        int retval = pgpImportExport.storeKeyRingInCache(publicRing);
        if (retval != Id.return_value.ok && retval != Id.return_value.updated) {
          throw new PgpGeneralException("Failed to store signed key in local cache");
        }

        sendMessageToHandler(ApgIntentServiceHandler.MESSAGE_OKAY);
      } catch (Exception e) {
        sendErrorToHandler(e);
      }
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(t, "onCreate: " + ((savedInstanceState == null) ? "creating" : "re-initializing"));

    mAlertMsg = getString(R.string.please_wait);
    mAlertShowing = false;

    mUploadedInstances = new HashMap<String, String>();

    setTitle(getString(R.string.app_name) + " > " + getString(R.string.send_data));

    // get any simple saved state...
    if (savedInstanceState != null) {
      if (savedInstanceState.containsKey(ALERT_MSG)) {
        mAlertMsg = savedInstanceState.getString(ALERT_MSG);
      }
      if (savedInstanceState.containsKey(ALERT_SHOWING)) {
        mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING, false);
      }

      mUrl = savedInstanceState.getString(AUTH_URI);
    }

    // and if we are resuming, use the TO_SEND list of not-yet-sent submissions
    // Otherwise, construct the list from the incoming intent value
    long[] selectedInstanceIDs = null;
    if (savedInstanceState != null && savedInstanceState.containsKey(TO_SEND)) {
      selectedInstanceIDs = savedInstanceState.getLongArray(TO_SEND);
    } else {
      // get instances to upload...
      Intent intent = getIntent();
      selectedInstanceIDs = intent.getLongArrayExtra(FormEntryActivity.KEY_INSTANCES);
    }

    mInstancesToSend = new Long[(selectedInstanceIDs == null) ? 0 : selectedInstanceIDs.length];
    if (selectedInstanceIDs != null) {
      for (int i = 0; i < selectedInstanceIDs.length; ++i) {
        mInstancesToSend[i] = selectedInstanceIDs[i];
      }
    }

    // at this point, we don't expect this to be empty...
    if (mInstancesToSend.length == 0) {
      Log.e(t, "onCreate: No instances to upload!");
      // drop through -- everything will process through OK
    } else {
      Log.i(t, "onCreate: Beginning upload of " + mInstancesToSend.length + " instances!");
    }

    // get the task if we've changed orientations. If it's null it's a new upload.
    mInstanceUploaderTask = (InstanceUploaderTask) getLastNonConfigurationInstance();
    if (mInstanceUploaderTask == null) {
      // setup dialog and upload task
      showDialog(PROGRESS_DIALOG);
      mInstanceUploaderTask = new InstanceUploaderTask();

      // register this activity with the new uploader task
      mInstanceUploaderTask.setUploaderListener(InstanceUploaderActivity.this);

      mInstanceUploaderTask.execute(mInstancesToSend);
    }
  }
  @SmallTest
  @MediumTest
  @LargeTest
  public void testAllTypes() {
    Bundle originalBundle = new Bundle();

    putBoolean(BOOLEAN_KEY, originalBundle);
    putBooleanArray(BOOLEAN_ARRAY_KEY, originalBundle);
    putByte(BYTE_KEY, originalBundle);
    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();

    SharedPreferencesTokenCachingStrategy cache =
        new SharedPreferencesTokenCachingStrategy(getContext());
    cache.save(originalBundle);

    SharedPreferencesTokenCachingStrategy cache2 =
        new SharedPreferencesTokenCachingStrategy(getContext());
    Bundle cachedBundle = cache2.load();

    Assert.assertEquals(
        originalBundle.getBoolean(BOOLEAN_KEY), cachedBundle.getBoolean(BOOLEAN_KEY));
    assertArrayEquals(
        originalBundle.getBooleanArray(BOOLEAN_ARRAY_KEY),
        cachedBundle.getBooleanArray(BOOLEAN_ARRAY_KEY));
    Assert.assertEquals(originalBundle.getByte(BYTE_KEY), cachedBundle.getByte(BYTE_KEY));
    assertArrayEquals(
        originalBundle.getByteArray(BYTE_ARRAY_KEY), cachedBundle.getByteArray(BYTE_ARRAY_KEY));
    Assert.assertEquals(originalBundle.getShort(SHORT_KEY), cachedBundle.getShort(SHORT_KEY));
    assertArrayEquals(
        originalBundle.getShortArray(SHORT_ARRAY_KEY), cachedBundle.getShortArray(SHORT_ARRAY_KEY));
    Assert.assertEquals(originalBundle.getInt(INT_KEY), cachedBundle.getInt(INT_KEY));
    assertArrayEquals(
        originalBundle.getIntArray(INT_ARRAY_KEY), cachedBundle.getIntArray(INT_ARRAY_KEY));
    Assert.assertEquals(originalBundle.getLong(LONG_KEY), cachedBundle.getLong(LONG_KEY));
    assertArrayEquals(
        originalBundle.getLongArray(LONG_ARRAY_KEY), cachedBundle.getLongArray(LONG_ARRAY_KEY));
    Assert.assertEquals(originalBundle.getFloat(FLOAT_KEY), cachedBundle.getFloat(FLOAT_KEY));
    assertArrayEquals(
        originalBundle.getFloatArray(FLOAT_ARRAY_KEY), cachedBundle.getFloatArray(FLOAT_ARRAY_KEY));
    Assert.assertEquals(originalBundle.getDouble(DOUBLE_KEY), cachedBundle.getDouble(DOUBLE_KEY));
    assertArrayEquals(
        originalBundle.getDoubleArray(DOUBLE_ARRAY_KEY),
        cachedBundle.getDoubleArray(DOUBLE_ARRAY_KEY));
    Assert.assertEquals(originalBundle.getChar(CHAR_KEY), cachedBundle.getChar(CHAR_KEY));
    assertArrayEquals(
        originalBundle.getCharArray(CHAR_ARRAY_KEY), cachedBundle.getCharArray(CHAR_ARRAY_KEY));
    Assert.assertEquals(originalBundle.getString(STRING_KEY), cachedBundle.getString(STRING_KEY));
    assertListEquals(
        originalBundle.getStringArrayList(STRING_LIST_KEY),
        cachedBundle.getStringArrayList(STRING_LIST_KEY));
    Assert.assertEquals(
        originalBundle.getSerializable(SERIALIZABLE_KEY),
        cachedBundle.getSerializable(SERIALIZABLE_KEY));
  }
Example #16
0
  /**
   * Restore the state of all the tabs.
   *
   * @param currentId The tab id to restore.
   * @param inState The saved state of all the tabs.
   * @param restoreIncognitoTabs Restoring private browsing tabs
   * @param restoreAll All webviews get restored, not just the current tab (this does not override
   *     handling of incognito tabs)
   */
  void restoreState(
      Bundle inState, long currentId, boolean restoreIncognitoTabs, boolean restoreAll) {
    if (currentId == -1) {
      return;
    }
    long[] ids = inState.getLongArray(POSITIONS);
    long maxId = -Long.MAX_VALUE;
    HashMap<Long, Tab> tabMap = new HashMap<Long, Tab>();
    for (long id : ids) {
      if (id > maxId) {
        maxId = id;
      }
      final String idkey = Long.toString(id);
      Bundle state = inState.getBundle(idkey);
      if (state == null || state.isEmpty()) {
        // Skip tab
        continue;
      } else if (!restoreIncognitoTabs && state.getBoolean(Tab.INCOGNITO)) {
        // ignore tab
      } else if (id == currentId || restoreAll) {
        Tab t = createNewTab(state, false);
        if (t == null) {
          // We could "break" at this point, but we want
          // sNextId to be set correctly.
          continue;
        }
        tabMap.put(id, t);
        // Me must set the current tab before restoring the state
        // so that all the client classes are set.
        if (id == currentId) {
          setCurrentTab(t);
        }
      } else {
        // Create a new tab and don't restore the state yet, add it
        // to the tab list
        Tab t = new Tab(mController, state);
        tabMap.put(id, t);
        mTabs.add(t);
        // added the tab to the front as they are not current
        mTabQueue.add(0, t);
      }
    }

    // make sure that there is no id overlap between the restored
    // and new tabs
    sNextId = maxId + 1;

    if (mCurrentTab == -1) {
      if (getTabCount() > 0) {
        setCurrentTab(getTab(0));
      }
    }
    // restore parent/child relationships
    for (long id : ids) {
      final Tab tab = tabMap.get(id);
      final Bundle b = inState.getBundle(Long.toString(id));
      if ((b != null) && (tab != null)) {
        final long parentId = b.getLong(Tab.PARENTTAB, -1);
        if (parentId != -1) {
          final Tab parent = tabMap.get(parentId);
          if (parent != null) {
            parent.addChildTab(tab);
          }
        }
      }
    }
  }
Example #17
0
 /**
  * Retrieve extended data from the request.
  *
  * @param name The name of the desired item.
  * @return the value of an item that previously added with putExtra() or null if no long array
  *     value was found.
  * @see #putExtra(String, long[])
  */
 public long[] getLongArrayExtra(String name) {
   return mExtras == null ? null : mExtras.getLongArray(name);
 }
  @Override
  public View onCreateView(
      LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.backup_code_fragment, container, false);

    Bundle args = getArguments();
    mBackupCode = args.getString(ARG_BACKUP_CODE);
    mMasterKeyIds = args.getLongArray(ARG_MASTER_KEY_IDS);
    mExportSecret = args.getBoolean(ARG_EXPORT_SECRET);
    mExecuteBackupOperation = args.getBoolean(ARG_EXECUTE_BACKUP_OPERATION, true);

    mCodeEditText = new EditText[6];
    mCodeEditText[0] = (EditText) view.findViewById(R.id.backup_code_1);
    mCodeEditText[1] = (EditText) view.findViewById(R.id.backup_code_2);
    mCodeEditText[2] = (EditText) view.findViewById(R.id.backup_code_3);
    mCodeEditText[3] = (EditText) view.findViewById(R.id.backup_code_4);
    mCodeEditText[4] = (EditText) view.findViewById(R.id.backup_code_5);
    mCodeEditText[5] = (EditText) view.findViewById(R.id.backup_code_6);

    {
      TextView[] codeDisplayText = new TextView[6];
      codeDisplayText[0] = (TextView) view.findViewById(R.id.backup_code_display_1);
      codeDisplayText[1] = (TextView) view.findViewById(R.id.backup_code_display_2);
      codeDisplayText[2] = (TextView) view.findViewById(R.id.backup_code_display_3);
      codeDisplayText[3] = (TextView) view.findViewById(R.id.backup_code_display_4);
      codeDisplayText[4] = (TextView) view.findViewById(R.id.backup_code_display_5);
      codeDisplayText[5] = (TextView) view.findViewById(R.id.backup_code_display_6);

      // set backup code in code TextViews
      char[] backupCode = mBackupCode.toCharArray();
      for (int i = 0; i < codeDisplayText.length; i++) {
        codeDisplayText[i].setText(backupCode, i * 5, 4);
      }

      // set background to null in TextViews - this will retain padding from EditText style!
      for (TextView textView : codeDisplayText) {
        // noinspection deprecation, setBackground(Drawable) is API level >=16
        textView.setBackgroundDrawable(null);
      }
    }

    setupEditTextFocusNext(mCodeEditText);
    setupEditTextSuccessListener(mCodeEditText);

    mStatusAnimator = (ToolableViewAnimator) view.findViewById(R.id.status_animator);
    mTitleAnimator = (ToolableViewAnimator) view.findViewById(R.id.title_animator);
    mCodeFieldsAnimator = (ToolableViewAnimator) view.findViewById(R.id.code_animator);

    View backupInput = view.findViewById(R.id.button_backup_input);
    backupInput.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            switchState(BackupCodeState.STATE_INPUT, true);
          }
        });

    view.findViewById(R.id.button_backup_save)
        .setOnClickListener(
            new OnClickListener() {
              @Override
              public void onClick(View v) {
                mShareNotSave = false;
                startBackup();
              }
            });

    view.findViewById(R.id.button_backup_share)
        .setOnClickListener(
            new OnClickListener() {
              @Override
              public void onClick(View v) {
                mShareNotSave = true;
                startBackup();
              }
            });

    view.findViewById(R.id.button_backup_back)
        .setOnClickListener(
            new OnClickListener() {
              @Override
              public void onClick(View v) {
                FragmentManager fragMan = getFragmentManager();
                if (fragMan != null) {
                  fragMan.popBackStack();
                }
              }
            });

    view.findViewById(R.id.button_faq)
        .setOnClickListener(
            new OnClickListener() {
              @Override
              public void onClick(View v) {
                showFaq();
              }
            });
    return view;
  }