コード例 #1
0
  /**
   * Takes an UnencryptedMsg object and does all the work necessary to transform it into an
   * EncyrptedMsg object that is ready to be serialised and sent out to the Bitmessage network. The
   * two major parts of this process are encryption and proof of work. <br>
   * <br>
   * <b>NOTE!</b> Calling this method results in proof of work calculations being done for the
   * message. This can take a long time and lots of CPU power!<br>
   * <br>
   *
   * @param message - The original plain text Message object, provided so that its status can be
   *     updated during the process
   * @param unencMsg - The UnencryptedMsg object to be encrypted
   * @param toPubkey - The Pubkey object containing the public encryption key of the intended
   *     message recipient
   * @param doPOW - A boolean value indicating whether or not POW should be done for this message
   * @param timeToLive - The 'time to live' value (in seconds) to be used in creating this msg
   * @return A Msg object containing the encrypted message data
   */
  private BMObject constructMsg(
      Message message, UnencryptedMsg unencMsg, Pubkey toPubkey, boolean doPOW, long timeToLive) {
    // Reconstruct the ECPublicKey object from the byte[] found the the relevant PubKey
    ECPublicKey publicEncryptionKey =
        new KeyConverter().reconstructPublicKey(toPubkey.getPublicEncryptionKey());

    // Construct the payload to be encrypted
    byte[] msgDataForEncryption = constructMsgPayloadForEncryption(unencMsg);

    // Update the status of this message displayed in the UI
    String messageStatus = App.getContext().getString(R.string.message_status_encrypting_message);
    MessageStatusHandler.updateMessageStatus(message, messageStatus);

    // Encrypt the payload
    CryptProcessor cryptProc = new CryptProcessor();
    byte[] encryptedPayload = cryptProc.encrypt(msgDataForEncryption, publicEncryptionKey);

    // Create a new Msg object and populate its fields
    BMObject msg = new BMObject();
    msg.setBelongsToMe(
        true); // NOTE: This method assumes that any message I am encrypting 'belongs to me' (i.e.
    // The user of the application is the author of the message)
    msg.setExpirationTime(unencMsg.getExpirationTime());
    msg.setObjectType(unencMsg.getObjectType());
    msg.setObjectVersion(unencMsg.getObjectVersion());
    msg.setStreamNumber(toPubkey.getStreamNumber());
    msg.setPayload(encryptedPayload);

    if (doPOW) {
      MessageStatusHandler.updateMessageStatus(
          message, App.getContext().getString(R.string.message_status_doing_pow));

      // Do proof of work for the Msg object
      Log.i(TAG, "About to do POW calculations for a msg that we are sending");
      byte[] powPayload = constructMsgPayloadForPOW(msg);
      long powNonce =
          new POWProcessor()
              .doPOW(
                  powPayload,
                  unencMsg.getExpirationTime(),
                  toPubkey.getNonceTrialsPerByte(),
                  toPubkey.getExtraBytes());
      msg.setPOWNonce(powNonce);
    } else {
      msg.setPOWNonce(
          (long) 0); // If POW is not to be done for this message, set the powNonce as zero for now.
    }

    return msg;
  }
コード例 #2
0
          @Override
          public void onClick(DialogInterface dialog, int which) {

            // O titulo da atividade não-escolar é requerida.
            if (title.getText().length() == 0) {
              Toast.makeText(
                      App.getContext(),
                      App.getContext().getResources().getText(R.string.words_invalid_field),
                      Toast.LENGTH_SHORT)
                  .show();
              return;
            }

            // O tempo inicial tem que ser menor que o tempo final.
            if (start.getTimeInMillis() >= end.getTimeInMillis()) {
              Toast.makeText(
                      App.getContext(),
                      App.getContext().getResources().getText(R.string.words_invalid_field),
                      Toast.LENGTH_SHORT)
                  .show();
              return;
            }

            // Modo adição. Adiciona a atividade não-escolar ao banco de dados.
            if (naoEscolar == null) {
              App.getDatabase()
                  .addNaoEscolar(
                      title.getText().toString(),
                      description.getText().toString(),
                      start.getTimeInMillis(),
                      end.getTimeInMillis());
            } // Modo edição. Edita a atividade não-escolar e atualiza no banco de dados.
            else {
              naoEscolar.setNome(title.getText().toString());
              naoEscolar.setDescricao(description.getText().toString());
              naoEscolar.setDiaIni(start.getTimeInMillis());
              naoEscolar.setDiaFim(end.getTimeInMillis());
              App.getDatabase().updateNaoEscolar(naoEscolar);
            }

            // Recarrega a lista de atividades não-escolares.
            update();
          }
コード例 #3
0
  private Notification getNotifcation(String url) {
    Notification notification = null;
    if (notificationMap.get(url) == null) {
      notification = new Notification();
      notification.icon = android.R.drawable.stat_sys_download;
      // mNotification.tickerText = mContext.getString(R.string.app_name)
      // + "更新";
      notification.when = System.currentTimeMillis();
      notification.defaults = Notification.DEFAULT_LIGHTS;
      Intent intent =
          new Intent(App.getContext().getApplicationContext(), App.getContext().getClass());
      PendingIntent contentIntent =
          PendingIntent.getActivity(App.getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
      notification.contentIntent = contentIntent;
      notificationMap.put(url, notification);
    } else {
      notification = notificationMap.get(url);
    }

    return notification;
  }
コード例 #4
0
  /**
   * Calculates the acknowledgement Message for a given message. <br>
   * <br>
   * The process for this is as follows:<br>
   * <br>
   * 1) initialPayload = time || stream number || 32 bytes of random data<br>
   * <br>
   * 2) Do POW for the initialPayload<br>
   * <br>
   * 3) ackData = POWnonce || msgHeader || initialPayload<br>
   * <br>
   *
   * @param message - The original plain text Message object, provided so that its status can be
   *     updated during the process
   * @param ackData - A byte[] containing the 32 bytes of random data which is the acknowledgment
   *     data
   * @param toStreamNumber - An int representing the stream number of the destination address of the
   *     message to be sent
   * @param doPOW - A boolean indicating whether or not POW should be done for ack msgs generated
   *     during this process
   * @param timeToLive - The 'time to live' value (in seconds) to be used in processing this message
   * @return A byte[] containing the acknowledgement data for the message we wish to send
   */
  private byte[] generateFullAckMessage(
      Message message, byte[] ackData, int toStreamNumber, boolean doPOW, long timeToLive) {
    // Get the fuzzed expiration time
    long expirationTime = TimeUtils.getFuzzedExpirationTime(timeToLive);

    // Encode the expiration time, object type, object version, and stream number values into byte
    // form
    byte[] expirationTimeBytes = ByteUtils.longToBytes((expirationTime));
    byte[] objectTypeBytes = ByteUtils.intToBytes(OBJECT_TYPE_MSG);
    byte[] objectVersionBytes = VarintEncoder.encode(OBJECT_VERSION_MSG);
    byte[] streamNumberBytes = VarintEncoder.encode((long) toStreamNumber);

    // Combine the time, object type, object version, stream number, and ack data values into a
    // single byte[]
    byte[] initialPayload =
        ByteUtils.concatenateByteArrays(
            expirationTimeBytes, objectTypeBytes, objectVersionBytes, streamNumberBytes, ackData);

    // Create the payload for the ack msg
    byte[] payload = new byte[0];
    if (doPOW) {
      // Update the status of this message displayed in the UI
      String messageStatus = App.getContext().getString(R.string.message_status_doing_ack_pow);
      MessageStatusHandler.updateMessageStatus(message, messageStatus);

      // Do proof of work for the acknowledgement payload
      Log.i(
          TAG,
          "About to do POW calculations for the acknowledgment payload of a msg that we are sending");
      long powNonce =
          new POWProcessor()
              .doPOW(
                  initialPayload,
                  expirationTime,
                  POWProcessor.NETWORK_NONCE_TRIALS_PER_BYTE,
                  POWProcessor.NETWORK_EXTRA_BYTES);

      byte[] powNonceBytes = ByteUtils.longToBytes(powNonce);

      payload = ByteUtils.concatenateByteArrays(powNonceBytes, initialPayload);
    } else {
      payload = initialPayload;
    }

    byte[] headerData = new MessageProcessor().generateObjectHeader(payload);
    byte[] fullAckMsg = ByteUtils.concatenateByteArrays(headerData, payload);

    return fullAckMsg;
  }
コード例 #5
0
 /**
  * @param item
  * @param messageState -1 不发送信息
  */
 private void updateDownloadState(DownloadItem item, int messageState) {
   if (null == item) {
     return;
   }
   String url = item.url;
   switch (item.state) {
     case DownloadItem.DOWNLOAD_STATE_FINISH:
       DownDB.getInstance(App.getContext())
           .upDate(item.name, url, "" + "", DownloadItem.DOWNLOAD_STATE_FINISH);
       FileUitls.moveFile(url, item.name, App.getContext());
       if (DownloadingItems.contains(url)) {
         DownloadingItems.remove(url);
       }
       if (pauseItems.contains(url)) {
         pauseItems.remove(url);
       }
       break;
     case DownloadItem.DOWNLOAD_STATE_ERROR:
       DownDB.getInstance(App.getContext()).delItem(item.url);
       FileUitls.delFile(item.url, App.getContext());
       if (DownloadingItems.contains(url)) {
         DownloadingItems.remove(url);
       }
       if (pauseItems.contains(url)) {
         pauseItems.remove(url);
       }
       break;
   }
   if (messageState != -1) {
     Message message = new Message();
     message.what = messageState;
     message.obj = item;
     mHandler.sendMessage(message);
   }
   DownLoadManager.sendDownloadUpdateBroadCast(item);
 }
コード例 #6
0
    public AddOrEditNaoEscolarDialog(Context context, Estudo naoEscolar) {
      this.naoEscolar = naoEscolar;

      // Cria o construtor da janela de dialogo.
      builder = new AlertDialog.Builder(context);
      // Habilita dois botões.
      builder.setNegativeButton(R.string.words_cancel, null);
      builder.setPositiveButton(R.string.words_ok, ok);

      // Define o titulo da janela.
      builder.setTitle(
          naoEscolar == null ? R.string.words_add_naoescolar : R.string.words_edit_naoescolar);
      // Infla o conteudo da janela e adiciona-o.
      LayoutInflater li =
          (LayoutInflater) App.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      View v = li.inflate(R.layout.layout_add_naoescolar_dialog, null);
      builder.setView(v);

      // Obtem os controles da janela.
      title = (EditText) v.findViewById(R.id.naoescolar_title);
      description = (EditText) v.findViewById(R.id.naoescolar_desc);
      startStatus = (TextView) v.findViewById(R.id.start_datetime_status);
      endStatus = (TextView) v.findViewById(R.id.end_datetime_status);

      // Modo edição. Preenche os campos.
      if (naoEscolar != null) {
        title.setText("" + naoEscolar.getCodigoMateria());
        description.setText(naoEscolar.getDescricao());
        start = (Calendar) naoEscolar.getDiaIni().clone();
        end = (Calendar) naoEscolar.getDiaFim().clone();
        // Escreve o texto nos TextViews.
        setDateTime(start, end);
      } // Modo adição.
      else {
        // Recupera a data e hora atual.
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        // Atrubui ao fim a data atual.
        end = calendar;
        // Atribui ao inicio a data atual.
        start = (Calendar) calendar.clone();
        // Acrescenta 1 hora.
        end.add(Calendar.HOUR, 1);
        // Escreve o texto nos TextViews.
        setDateTime(start, end);
      }
    }
コード例 #7
0
  /**
   * Takes a Msg and encodes it into a single byte[], in a way that is compatible with the way that
   * PyBitmessage does. This payload can then be sent to a server to be disseminated across the
   * network. The payload is stored as a Payload object.
   *
   * @param encMsg - A msg Object containing the message data used to create the payload.
   * @param powDone - A boolean value indicating whether or not POW has been done for this message
   * @param toPubkey - A Pubkey object containing the data for the Pubkey of the address that this
   *     message is being sent to
   * @return A Payload object containing the message payload
   */
  private Payload constructMsgPayloadForDissemination(
      BMObject encMsg, boolean powDone, Pubkey toPubkey) {
    // Create a new Payload object to hold the payload data
    Payload msgPayload = new Payload();
    msgPayload.setBelongsToMe(true);
    msgPayload.setPOWDone(powDone);
    msgPayload.setType(Payload.OBJECT_TYPE_MSG);

    // Encode the POW nonce, expiration time, object type, object version, and stream number values
    // into byte form
    byte[] powNonceBytes = ByteUtils.longToBytes(encMsg.getPOWNonce());
    byte[] expirationTimeBytes = ByteUtils.longToBytes(encMsg.getExpirationTime());
    byte[] objectTypeBytes = ByteUtils.intToBytes(OBJECT_TYPE_MSG);
    byte[] objectVersionBytes = VarintEncoder.encode(OBJECT_VERSION_MSG);
    byte[] streamNumberBytes = VarintEncoder.encode(encMsg.getStreamNumber());

    byte[] payload = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
      if (powDone) {
        outputStream.write(powNonceBytes);
      }
      outputStream.write(expirationTimeBytes);
      outputStream.write(objectTypeBytes);
      outputStream.write(objectVersionBytes);
      outputStream.write(streamNumberBytes);
      outputStream.write(encMsg.getPayload());

      payload = outputStream.toByteArray();
      outputStream.close();
    } catch (IOException e) {
      throw new RuntimeException(
          "IOException occurred in DataProcessor.constructMsgPayloadForDissemination()", e);
    }

    msgPayload.setPayload(payload);

    // Save the Payload object to the database
    PayloadProvider payProv = PayloadProvider.get(App.getContext());
    long msgPayloadId = payProv.addPayload(msgPayload);

    // Finally, set the msg payload ID to the one generated by the SQLite database
    msgPayload.setId(msgPayloadId);

    return msgPayload;
  }
コード例 #8
0
  /**
   * Constructs an UnencryptedMsg object from a given Message object. Used when sending a message.
   * <br>
   * <br>
   * <b>NOTE!</b> Calling this method results in proof of work calculations being done for the
   * acknowledgement data of the message. This can take a long time and lots of CPU power!<br>
   * <br>
   * <b>NOTE!</b> Calling this method can result in requests to a Bitseal server to retrieve pubkey
   * data. These requests may take some time to complete!
   *
   * @param message - The Message object to convert into an UnencryptedMsg object
   * @param toPubkey - A Pubkey object containing the public keys of the address the message is
   *     being sent to
   * @param doPOW - A boolean indicating whether or not POW should be done for msgs generated during
   *     this process
   * @param timeToLive - The 'time to live' value (in seconds) to be used in processing this message
   * @return An UnencryptedMsg object based on the supplied Message object.
   */
  private UnencryptedMsg constructUnencryptedMsg(
      Message message, Pubkey toPubkey, boolean doPOW, long timeToLive) {
    String messageSubject = message.getSubject();
    String messageBody = message.getBody();

    // First let us check that the to address and from address Strings taken from the Message object
    // are in fact valid Bitmessage addresses
    String toAddressString = message.getToAddress();
    String fromAddressString = message.getFromAddress();
    AddressProcessor addProc = new AddressProcessor();

    if (addProc.validateAddress(toAddressString) != true) {
      throw new RuntimeException(
          "During the execution of constructUnencryptedMsg(), it was found that the 'to' address in the supplied Message was not a valid Bitmessage address");
    }
    if (addProc.validateAddress(fromAddressString) != true) {
      throw new RuntimeException(
          "During the execution of constructUnencryptedMsg(), it was found that the 'from' address in the supplied Message was not a valid Bitmessage address");
    }

    // Now that we have validated the to address and the from address, let us retrieve or create
    // their corresponding Address and Pubkey objects.
    Address fromAddress = null;
    AddressProvider addProv = AddressProvider.get(App.getContext());
    ArrayList<Address> retrievedAddresses =
        addProv.searchAddresses(AddressesTable.COLUMN_ADDRESS, fromAddressString);
    if (retrievedAddresses.size() != 1) {
      Log.e(
          TAG,
          "There should be exactly 1 record found in this search. Instead "
              + retrievedAddresses.size()
              + " records were found");
    } else {
      fromAddress = retrievedAddresses.get(0);
    }

    // Now we need to get the behaviour bitfield from the pubkey which corresponds to the from
    // address, so let us retrieve that pubkey.
    PubkeyProvider pubProv = PubkeyProvider.get(App.getContext());
    ArrayList<Pubkey> retrievedPubkeys =
        pubProv.searchPubkeys(
            PubkeysTable.COLUMN_CORRESPONDING_ADDRESS_ID, String.valueOf(fromAddress.getId()));
    Pubkey fromPubkey = null;
    if (retrievedPubkeys.size() == 1) {
      fromPubkey = retrievedPubkeys.get(0);
    } else if (retrievedPubkeys.size() > 1) // If there are duplicate pubkeys for this address
    {
      Log.e(
          TAG,
          "There should be exactly 1 record found in this search. Instead "
              + retrievedPubkeys.size()
              + " records were found");

      // Delete all but the most recent of the duplicate pubkeys
      long firstPubkeyTime = retrievedPubkeys.get(0).getExpirationTime();
      Pubkey pubkeyToKeep = retrievedPubkeys.get(0);
      for (Pubkey p : retrievedPubkeys) {
        if (p.getExpirationTime() > firstPubkeyTime) {
          pubkeyToKeep = p;
        }
      }
      for (Pubkey p : retrievedPubkeys) {
        if (p.equals(pubkeyToKeep) == false) {
          pubProv.deletePubkey(p);
        }
      }

      // Use the most recent of the duplicate pubkeys
      fromPubkey = pubkeyToKeep;
    }

    if (fromPubkey == null) {
      Log.e(
          TAG,
          "Could not find the Pubkey which corresponds to the from address, even though it should be one of our own. Something is wrong!");
      Log.d(TAG, "Regenerating the Pubkey for the from address");
      fromPubkey =
          new PubkeyGenerator()
              .generateAndSaveNewPubkey(
                  fromAddress); // If we can't find the pubkey we need then let us generate it again
    }

    // Now extract the public signing and public encryption keys from the "from" pubkey
    // If the public signing and encryption keys taken from the Pubkey object have an "\x04" byte at
    // their beginning, we need to remove it now.
    byte[] publicSigningKey = fromPubkey.getPublicSigningKey();
    byte[] publicEncryptionKey = fromPubkey.getPublicEncryptionKey();

    if (publicSigningKey[0] == (byte) 4 && publicSigningKey.length == 65) {
      publicSigningKey = ArrayCopier.copyOfRange(publicSigningKey, 1, publicSigningKey.length);
    }

    if (publicEncryptionKey[0] == (byte) 4 && publicEncryptionKey.length == 65) {
      publicEncryptionKey =
          ArrayCopier.copyOfRange(publicEncryptionKey, 1, publicEncryptionKey.length);
    }

    // Generate the ack data (32 random bytes)
    byte[] ackData = new byte[32];
    new SecureRandom().nextBytes(ackData);

    // Generate the full ack Message that will be included in this unencrypted msg.
    // NOTE: Calling generateFullAckMessage() results in Proof of Work calculations being done for
    // the
    //       acknowledgement Message. This can take a long time and lots of CPU power!
    byte[] fullAckMessage =
        generateFullAckMessage(message, ackData, fromPubkey.getStreamNumber(), doPOW, timeToLive);
    Log.d(TAG, "Full ack Message: " + ByteFormatter.byteArrayToHexString(fullAckMessage));

    // Create the single "message" text String which contains both the subject and the body of the
    // message
    // See https://bitmessage.org/wiki/Protocol_specification#Message_Encodings
    String messsageText = "Subject:" + messageSubject + "\n" + "Body:" + messageBody;

    // Now create the UnencryptedMsg object and populate its fields.
    UnencryptedMsg unencMsg = new UnencryptedMsg();

    unencMsg.setBelongsToMe(true);
    unencMsg.setExpirationTime(TimeUtils.getFuzzedExpirationTime(timeToLive));
    unencMsg.setObjectType(OBJECT_TYPE_MSG);
    unencMsg.setObjectVersion(OBJECT_VERSION_MSG);
    unencMsg.setStreamNumber(toPubkey.getStreamNumber());
    unencMsg.setSenderAddressVersion(fromPubkey.getObjectVersion());
    unencMsg.setSenderStreamNumber(fromPubkey.getStreamNumber());
    unencMsg.setBehaviourBitfield(fromPubkey.getBehaviourBitfield());
    unencMsg.setPublicSigningKey(publicSigningKey);
    unencMsg.setPublicEncryptionKey(publicEncryptionKey);
    unencMsg.setNonceTrialsPerByte(fromPubkey.getNonceTrialsPerByte());
    unencMsg.setExtraBytes(fromPubkey.getExtraBytes());
    unencMsg.setDestinationRipe(new KeyConverter().calculateRipeHashFromPubkey(toPubkey));
    unencMsg.setEncoding(MESSAGE_ENCODING_TYPE);
    unencMsg.setMessageLength(
        messsageText.getBytes()
            .length); // We have to use the byte length rather than the string length - some
    // characters take more bytes than others
    unencMsg.setMessage(
        messsageText
            .getBytes()); // PyBitmessage also uses UTF-8 as its character set, so this ought to be
    // adequate
    unencMsg.setAckLength(fullAckMessage.length);
    unencMsg.setAckMsg(fullAckMessage);

    // Save the acknowledgment data to the database so that when we receive the acknowledgment for
    // this message we will recognise it
    Payload ackPayload = new Payload();
    ackPayload.setBelongsToMe(true); // i.e. This is an acknowledgment created by me
    ackPayload.setPOWDone(true);
    ackPayload.setAck(true); // This payload is an acknowledgment
    ackPayload.setType(
        Payload.OBJECT_TYPE_MSG); // Currently we treat all acks from other people as msgs. Strictly
    // though they can be objects of any type, so this may change
    ackPayload.setPayload(ackData);
    PayloadProvider payProv = PayloadProvider.get(App.getContext());
    long ackPayloadId = payProv.addPayload(ackPayload);

    // Set the "ackPayloadId" field of the original Message object so that we know which Message
    // this ack data is for
    message.setAckPayloadId(ackPayloadId);
    MessageProvider msgProv = MessageProvider.get(App.getContext());
    msgProv.updateMessage(message);

    // Now create the signature for this message
    SigProcessor sigProc = new SigProcessor();
    byte[] signaturePayload = sigProc.createUnencryptedMsgSignaturePayload(unencMsg);
    byte[] signature = sigProc.signWithWIFKey(signaturePayload, fromAddress.getPrivateSigningKey());

    unencMsg.setSignature(signature);
    unencMsg.setSignatureLength(signature.length);

    return unencMsg;
  }
コード例 #9
0
        @Override
        public synchronized void handleMessage(Message msg) {
          super.handleMessage(msg);
          DownloadItem downitem = (DownloadItem) msg.obj;
          if (msg != null) {

            switch (msg.what) {
              case DOWNLOAD_UPDATE:
                if (mNotificationManager == null) {
                  // L.i("init mNotificationManager", "1111111111");
                  mNotificationManager =
                      (NotificationManager)
                          App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
                }

                Notification notifcation = getNotifcation(downitem.url);
                notifcation.tickerText = downitem.name + "";
                mRemoveViews = new RemoteViews(App.getContext().getPackageName(), R.layout.update);
                mRemoveViews.setTextViewText(R.id.down_title, downitem.name);
                mRemoveViews.setTextViewText(
                    R.id.tvProcess, "已下载" + downitem.downloadPercent + "%");
                mRemoveViews.setProgressBar(R.id.pbDownload, 100, downitem.downloadPercent, false);

                //					if (null != downitem.type
                //							&& DOWNLOAD_MM.equals(downitem.type)) {
                mRemoveViews.setImageViewResource(R.id.ivLogo, R.mipmap.ic_launcher);
                //					}
                // else {
                // mRemoveViews.setImageViewResource(R.id.ivLogo,
                // R.drawable.about_tv_logo);
                // }
                notifcation.contentView = mRemoveViews;
                mNotificationManager.notify(downitem.url.hashCode(), notifcation);

                // if (mNotificationManager != null) {
                // mNotification.tickerText = msg.obj.toString();
                // mRemoveViews.setTextViewText(R.id.tvProcess, "已下载"+
                // mDownloadPrecent + "%");
                // mRemoveViews.setProgressBar(R.id.pbDownload,
                // 100,mDownloadPrecent, false);
                // mNotification.contentView = mRemoveViews;
                // mNotificationManager.notify(mNotificationId,mNotification);
                // }
                break;
              case DOWNLOAD_COMPLETE:
                if (mNotificationManager != null && notificationMap.get(downitem.url) != null) {
                  mNotificationManager.cancel(downitem.url.hashCode());
                  notificationMap.remove(downitem.url);
                }
                File newFile = FileUitls.getCompleteSaveFile(downitem.name);
                //                        install(newFile, App.getContext());
                break;
              case DOWNLOAD_FAIL:
                if (mNotificationManager != null && notificationMap.get(downitem.url) != null) {
                  mNotificationManager.cancel(downitem.url.hashCode());
                  notificationMap.remove(downitem.url);
                }
                //                        if (customDialog != null)
                //                            customDialog.dismiss();
                //                        CommonUtils.showToast(R.string.downloadfail);
                break;
              case NETWORK_ERROR:
                if (mNotificationManager != null && notificationMap.get(downitem.url) != null) {
                  mNotificationManager.cancel(downitem.url.hashCode());
                  notificationMap.remove(downitem.url);
                }
                //                        if (customDialog != null)
                //                            customDialog.dismiss();
                //                        CommonUtils.showToast(R.string.network_error);
                break;
                // case SHOW_WAITING:
                // customDialog.show();
                // break;
                // case DISMISS_WAITINGL:
                // customDialog.dismiss();
                // break;
                //                    case REQEUSTFAIL:
                //                        CommonUtils.showToast(R.string.downloadfail);

              case SDCARD_NOSPACE:
                if (mNotificationManager != null && notificationMap.get(downitem.url) != null) {
                  mNotificationManager.cancel(downitem.url.hashCode());
                  notificationMap.remove(downitem.url);
                }
                //                        if (customDialog != null)
                //                            customDialog.dismiss();
                //                        // CommonUtil.showToast(R.string.downloadfail, 0);
                //                        CommonUtils.showToast(R.string.nofreespace);
                break;
              default:
                break;
            }
          }
        }
コード例 #10
0
  private void downLoadDatas(String urlStr, String name) {
    if (pauseItems.contains(urlStr)) {
      pauseItems.remove(urlStr);
      L.i(this, "pause delet ", urlStr, name);
    }
    L.i(this, "before download", DownloadingItems.toString());
    if (DownloadingItems.contains(urlStr)) {
      L.i(this, "is download", urlStr, name);
      return;
    }
    L.i(this, "start download ", urlStr, name);
    DownloadingItems.add(urlStr);
    URL url = null;
    try {
      url = new URL(urlStr);
    } catch (MalformedURLException e) {
      e.printStackTrace();
      L.e(this, "url", "error", urlStr, name);
      DownLoadManager.sendDownloadBroadCast(urlStr, DownLoadManager.ERROR_URL);
      return;
    }
    HttpURLConnection urlConnection = null;
    try {
      urlConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
      L.e(this, "url", "openConnection error", urlStr, name);
      e.printStackTrace();
      DownLoadManager.sendDownloadBroadCast(urlStr, DownLoadManager.ERROR_NETWORK);

      return;
    }
    urlConnection.setConnectTimeout(8000);
    urlConnection.setReadTimeout(8000);
    long startRange = 0;
    long currentSize = 0;
    File file = FileUitls.getFile(urlStr, this);
    if (file.exists()) {
      startRange = file.length();
    } else {
      startRange = 0;
    }
    urlConnection.setRequestProperty("Range", "bytes=" + startRange + "-");
    float fileSize = 0;
    DownloadItem downLoadDatas = DownDB.getInstance(App.getContext()).selectItem(urlStr);
    if (startRange == 0) {
      fileSize = urlConnection.getContentLength();
      if (null == downLoadDatas) {
        if (startRange == 0) {
          DownDB.getInstance(App.getContext())
              .InsetData(name, urlStr, fileSize + "", DownloadItem.DOWNLOAD_STATE_NOTINT);
        }
      }
    } else {
      downLoadDatas = DownDB.getInstance(App.getContext()).selectItem(urlStr);
      fileSize =
          Float.parseFloat(
              TextUtils.isEmpty(downLoadDatas.totalSize) ? "0" : downLoadDatas.totalSize);
    }
    InputStream inputStream = null;
    try {
      inputStream = urlConnection.getInputStream();
    } catch (IOException e) {
      e.printStackTrace();
      L.e(this, "network error", urlStr, name);
      DownLoadManager.sendDownloadBroadCast(urlStr, DownLoadManager.ERROR_NETWORK);
      return;
    }
    byte[] b = new byte[1024];
    int lenth = 0;
    int shouldNotifySize = 0;
    FileOutputStream fileout = null;
    try {
      fileout = new FileOutputStream(file, true);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      L.e("download", " ERROR_FILE_NOFIND", urlStr, name);
      DownLoadManager.sendDownloadBroadCast(urlStr, DownLoadManager.ERROR_FILE_NOFIND);
    }
    L.i("download", "download begin");
    DownLoadManager.sendDownloadBroadCast(urlStr, DownLoadManager.DOWNLOAD_BEGIN);

    try {
      while (null != inputStream && (lenth = inputStream.read(b)) != -1) {
        if (file.exists() && file.length() != 0 && file.length() < currentSize) {
          L.i("TAG", file.length() + ":" + currentSize + "", urlStr, name);
          L.i(this, file.length() + ":" + currentSize + "", "redownload");
          downLoadDatas.state = DownloadItem.DOWNLOAD_STATE_ERROR;
          updateDownloadState(downLoadDatas, DOWNLOAD_FAIL);
          downLoadDatas(urlStr, name);
          return;
        }
        currentSize += lenth;
        fileout.write(b, 0, lenth);
        fileout.flush();
        shouldNotifySize += lenth;
        if (pauseItems.contains(urlStr)) {
          fileout.close();
          downLoadDatas.state = DownloadItem.DOWNLOAD_STATE_PAUSE;
          updateDownloadState(downLoadDatas, -1);
          return;
        }
        if (shouldNotifySize * 100 / fileSize >= 5) {
          shouldNotifySize = 0;
          downLoadDatas.currentSize = file.length() + "";
          downLoadDatas.state = DownloadItem.DOWNLOAD_STATE_DOING;
          downLoadDatas.downloadPercent = (int) (((double) file.length() / fileSize) * 100);
          updateDownloadState(downLoadDatas, DOWNLOAD_UPDATE);
        }
        file = FileUitls.getFile(urlStr, this);
      }
    } catch (IOException e) {
      e.printStackTrace();
      downLoadDatas.state = DownloadItem.DOWNLOAD_STATE_ERROR;
      updateDownloadState(downLoadDatas, DOWNLOAD_FAIL);
      L.e("TAG", urlStr, name, "redownload");

      downLoadDatas(urlStr, name);
      return;
    }
    try {
      fileout.close();
    } catch (IOException e) {
      e.printStackTrace();
      L.e(this, "close error", urlStr, name);
    }
    if (file.exists()) {
      if (file.length() != 0 && file.length() < currentSize) {
        downLoadDatas.state = DownloadItem.DOWNLOAD_STATE_ERROR;
        updateDownloadState(downLoadDatas, DOWNLOAD_FAIL);
        L.e("TAG", urlStr, name, "redownload");

        downLoadDatas(urlStr, name);
        return;
      }
      /** finsh donwload */
      if (fileSize == file.length()) {
        L.i(this, "fileSize == file.length()DOWNLOAD_STATE_FINISH", urlStr, name);
        int downloadPercent = (int) (((double) file.length() / fileSize) * 100);
        downLoadDatas.state = DownloadItem.DOWNLOAD_STATE_FINISH;
        downLoadDatas.downloadPercent = downloadPercent;
        updateDownloadState(downLoadDatas, DOWNLOAD_COMPLETE);
      } else {
        downLoadDatas.state = DownloadItem.DOWNLOAD_STATE_ERROR;
        updateDownloadState(downLoadDatas, DOWNLOAD_FAIL);
        L.e("TAG", urlStr, name, "redownload");
        downLoadDatas(downLoadDatas.url, downLoadDatas.name);
      }
    }
    L.i("download", "download success", urlStr, name);
  }
コード例 #11
0
  /**
   * DESCRIPTION: Constructs and populates a View for display of the GasRecord date at the index of
   * the List specified by the position parameter.
   *
   * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
   */
  @Override
  public View getView(int position, View view, ViewGroup parent) {

    // create a view for the row if it doesn't already exist
    if (view == null) {
      LayoutInflater inflater = activity.getLayoutInflater();
      view = inflater.inflate(R.layout.row_gas_log_list, null);
    }

    // get widgets from the view
    TextView columnDate = (TextView) view.findViewById(R.id.columnDate);
    TextView columnOdometer = (TextView) view.findViewById(R.id.columnOdometer);
    TextView columnGallons = (TextView) view.findViewById(R.id.columnGallons);
    TextView columnMileage = (TextView) view.findViewById(R.id.columnMileage);
    TextView rowCost = (TextView) view.findViewById(R.id.rowCost);
    TextView rowNotes = (TextView) view.findViewById(R.id.rowNotes);

    // populate row widgets from record data
    GasRecord record = records.get(position);

    // date
    columnDate.setText(record.getDateString());

    // odometer (bold if tank is full)
    if (record.isFullTank()) {
      columnOdometer.setText(Html.fromHtml("<b>" + record.getOdometerString() + "</b>"));
    } else {
      columnOdometer.setText(record.getOdometerString());
    }

    // gallons
    columnGallons.setText(record.getGallonsString());

    // mpg
    String mileage = "";
    if (record.hasCalculation()) {
      mileage = record.getCalculation().getMileageString();
      if (mileage.length() > "9999.99".length()) {
        mileage = "#VAL!";
      }
      if (record.isCalculationHidden()) {
        mileage = "---";
      }
    }
    columnMileage.setText(mileage);

    // cost (don't display if zero)
    if (!isCostDisplayable || (record.getCost() == 0d)) {
      rowCost.setVisibility(View.GONE);
    } else {
      String cost =
          String.format(
              "<b>%s</b>: %s (%s %s)",
              App.getContext().getString(R.string.cost_label),
              CurrencyManager.getInstance().getSymbolicFormatter().format(record.getCost()),
              CurrencyManager.getInstance()
                  .getSymbolicFractionalFormatter()
                  .format(record.getPrice()),
              units.getLiquidVolumeRatioLabel());
      rowCost.setText(Html.fromHtml(cost));
      rowCost.setVisibility(View.VISIBLE);
    }

    // notes (don't display if blank)
    String notes = record.getNotes();
    if (!isNotesDisplayable || (notes == null) || notes.trim().isEmpty()) {
      rowNotes.setVisibility(View.GONE);
    } else {
      notes =
          String.format("<b>%s</b>: %s", App.getContext().getString(R.string.notes_label), notes);
      rowNotes.setText(Html.fromHtml(notes));
      rowNotes.setVisibility(View.VISIBLE);
    }

    // return the view
    return view;
  }
コード例 #12
0
ファイル: ConnectActivity.java プロジェクト: debun8/gphotos
 private GoogleDataSession getSession() {
   return GoogleDataSession.getInstance(App.getContext());
 }