Example #1
1
 private static void drawToast(View v, Rect vRect) {
   // TODO Auto-generated method stub
   if (mToast != null) {
     View tv = mToast.getView();
     if (tv.getWidth() > 0 && tv.isShown()) {
       if (LOGD_ENABLED) Log.i(LOG_TAG, "==== " + tv.getWidth() + " " + tv.getHeight());
       Bitmap second = Utils.createPngScreenshot(tv, tv.getWidth(), tv.getHeight(), 0);
       if (LOGD_ENABLED)
         Log.d(
             LOG_TAG,
             "====== gravity "
                 + mToast.getGravity()
                 + " x y "
                 + mToast.getXOffset()
                 + " "
                 + mToast.getYOffset()
                 + " "
                 + mToast.getHorizontalMargin()
                 + " "
                 + mToast.getVerticalMargin());
       PointF fromPoint =
           new PointF(
               (v.getWidth() - tv.getWidth()) / 2,
               v.getHeight() - vRect.top - mToast.getYOffset() - tv.getHeight());
       if (LOGD_ENABLED)
         Log.i(LOG_TAG, "======= prepare menu view2  ========" + fromPoint.x + " " + fromPoint.y);
       mCapture = Utils.mixtureBitmap2(mCapture, second, fromPoint, 0, (float) 1.0);
     }
   }
 }
  @Override
  protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    Bundle extras = intent.getExtras();
    String msg = intent.getStringExtra("message");
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {

      if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
        sendNotification("Send error: " + extras.toString());
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
        sendNotification("Deleted messages on server: " + extras.toString());
        // If it's a regular GCM message, do some work.
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
        // This loop represents the service doing some work.
        for (int i = 0; i < 5; i++) {
          Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
          try {
            Thread.sleep(500);
          } catch (InterruptedException e) {
          }
        }
        Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
        // Post notification of received message.
        // sendNotification("Received: " + extras.toString());
        sendNotification(msg);
        Log.i(TAG, "Received: " + extras.toString());
      }
    }
    GcmBroadcastReciever.completeWakefulIntent(intent);
  }
  @Override
  public void setBinaryData(Object answer) {
    // you are replacing an answer. delete the previous image using the
    // content provider.
    if (mBinaryName != null) {
      deleteMedia();
    }

    File newImage = (File) answer;
    if (newImage.exists()) {
      // Add the new image to the Media content provider so that the
      // viewing is fast in Android 2.0+
      ContentValues values = new ContentValues(6);
      values.put(Images.Media.TITLE, newImage.getName());
      values.put(Images.Media.DISPLAY_NAME, newImage.getName());
      values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
      values.put(Images.Media.MIME_TYPE, "image/jpeg");
      values.put(Images.Media.DATA, newImage.getAbsolutePath());

      Uri imageURI =
          getContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
      Log.i(t, "Inserting image returned uri = " + imageURI.toString());

      mBinaryName = newImage.getName();
      Log.i(t, "Setting current answer to " + newImage.getName());
    } else {
      Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
    }

    Collect.getInstance().getFormController().setIndexWaitingForData(null);
  }
 public static void setBestPreviewFPS(Camera.Parameters parameters, int minFPS, int maxFPS) {
   List<int[]> supportedPreviewFpsRanges = parameters.getSupportedPreviewFpsRange();
   Log.i(TAG, "Supported FPS ranges: " + toString(supportedPreviewFpsRanges));
   if (supportedPreviewFpsRanges != null && !supportedPreviewFpsRanges.isEmpty()) {
     int[] suitableFPSRange = null;
     for (int[] fpsRange : supportedPreviewFpsRanges) {
       int thisMin = fpsRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX];
       int thisMax = fpsRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX];
       if (thisMin >= minFPS * 1000 && thisMax <= maxFPS * 1000) {
         suitableFPSRange = fpsRange;
         break;
       }
     }
     if (suitableFPSRange == null) {
       Log.i(TAG, "No suitable FPS range?");
     } else {
       int[] currentFpsRange = new int[2];
       parameters.getPreviewFpsRange(currentFpsRange);
       if (Arrays.equals(currentFpsRange, suitableFPSRange)) {
         Log.i(TAG, "FPS range already set to " + Arrays.toString(suitableFPSRange));
       } else {
         Log.i(TAG, "Setting FPS range to " + Arrays.toString(suitableFPSRange));
         parameters.setPreviewFpsRange(
             suitableFPSRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
             suitableFPSRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
       }
     }
   }
 }
  public boolean openOrCreateDatabase(Context context, File dbFile) {

    try {

      if (dbFile.exists()) {
        Log.i("SQLiteHelper", "Opening database at " + dbFile);
        mDb =
            SQLiteDatabase.openDatabase(
                dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        return true;

        // Test if DB works properly
        // get(MapTile.TABLE_TILE_NAME, "tilekey");
        // ---

        // if (DATABASE_VERSION > db.getVersion())
        // upgrade();
      } else {
        Log.i("SQLiteHelper", "Creating database at " + dbFile);
        mDb = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
        Log.i("SQLiteHelper", "Opened database at " + dbFile);
        upgradeFromFile(mDb, R.raw.sql_osm_maptile);
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
Example #6
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

    K holder = null;
    if (convertView == null) {
      convertView = LayoutInflater.from(mContext).inflate(getItemLayout(), parent, false);
      try {
        holder = classType.newInstance();
        Log.i("INFO", "Complete");
      } catch (InstantiationException e) {
        Log.i("INFO", "InstantiationException");
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        Log.i("INFO", "IllegalAccessException");
        e.printStackTrace();
      }
      initViewHolder(convertView, holder);
      convertView.setTag(holder);
    } else {
      holder = (K) convertView.getTag();
    }
    T entity = mEntities.get(position);
    setDataIntoView(holder, entity);
    return convertView;
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

    // Use this check to determine whether BLE is supported on the device.  Then you can
    // selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
      Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
      finish();
    }

    // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
    // BluetoothAdapter through BluetoothManager.
    final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) {
      Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
      finish();
      return;
    }

    Log.i("SCAN", "" + mBluetoothAdapter.isMultipleAdvertisementSupported());
    Log.i("SCAN", "" + mBluetoothAdapter.isOffloadedFilteringSupported());
    Log.i("SCAN", "" + mBluetoothAdapter.isOffloadedScanBatchingSupported());
  }
 @Override
 public void onUpdateDevice(StateDevice stateDevice) {
   if (stateDevice.getType() == StateDeviceProtos.StateDeviceMessage.Type.DOORBELL) {
     // If the state is set to inactive by the client
     Log.i(TAG, "Device updated");
     if (stateDevice.getState() == StateDeviceProtos.StateDeviceMessage.State.INACTIVE) {
       StateDeviceProtos.StateDeviceMessage msg =
           StateDeviceProtos.StateDeviceMessage.newBuilder()
               .setId(stateDevice.getId())
               .setName(stateDevice.getName())
               .setState(stateDevice.getState())
               .setType(stateDevice.getType())
               .build();
       // Send the message
       try {
         Log.i(TAG, "Sending message: \n" + msg.toString());
         OutputStream out = Client.getConnection().getOutputStream();
         msg.writeDelimitedTo(out);
       } catch (IOException e) {
         Client.removeConnection();
         Log.e(TAG, "unable to write to output stream", e);
       }
     }
   }
 }
Example #9
0
        public void processMessage(Chat chat, Message message) {
          if ((message.getBody() != null) && (!message.getType().equals(Message.Type.error))) {
            if (!cipher) {

              Log.i(TAG, "Recibido mensaje plano: " + message.getBody());
              listMessages.add(message);
              refreshAdapter();
              myListView.smoothScrollToPosition(adapter.getCount() - 1);
            } else {

              try {
                PrivateKey pk =
                    RSA.getPrivateKeyDecryted(KeyStore.getInstance().getPk(), passPhrase);
                String decodedMessage = RSA.decipher(message.getBody(), pk);
                Log.i(TAG, "Recibido mensaje cifrado: " + decodedMessage);

                Message m = new Message();
                m.setFrom(message.getFrom());
                m.setTo(message.getTo());

                m.setBody(decodedMessage);
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                m.setSubject(sdf.format(new Date()));
                listMessages.add(m);
                refreshAdapter();
                myListView.smoothScrollToPosition(adapter.getCount() - 1);

              } catch (Exception e) {
                Log.d(TAG, "PETO AL DESCIFRAR");
                e.printStackTrace();
              }
            }
          }
        }
Example #10
0
 @Override
 public void run() {
   Log.i(LOGTAG, "ConnectTask.run()...");
   XmppManager xmppManager = getXmppManager();
   if (!xmppManager.isConnected()) {
     ConnectionConfiguration connCfg =
         new ConnectionConfiguration(xmppManager.getXmppHost(), xmppManager.getXmppPort());
     connCfg.setSecurityMode(SecurityMode.required);
     connCfg.setSASLAuthenticationEnabled(false);
     connCfg.setCompressionEnabled(false);
     XMPPConnection connection = new XMPPConnection(connCfg);
     xmppManager.setConnection(connection);
     try {
       connection.connect();
       ProviderManager.getInstance()
           .addIQProvider(
               "notification", Constants.NOTIFICATION_NAMESPACE, new NotificationIQProvider());
       Log.i(LOGTAG, "XMPP connected successfully");
       xmppManager.getContext().sendBroadcast(new Intent(Constants.ACTION_CONNECT_SUCCESS));
     } catch (XMPPException e) {
       Log.e(LOGTAG, "XMPP connection failed", e);
       xmppManager.getContext().sendBroadcast(new Intent(Constants.ACTION_CONNECT_FAIL));
     }
     xmppManager.runTask();
   } else {
     Log.i(LOGTAG, "XMPP connected already");
     xmppManager.runTask();
   }
 }
  private void updateServerList() {
    Log.i("-> REMOTE SERVICE", "updateServerList()");

    for (int i = 0; i < mServers.length; i++) {
      Log.i("-> REMOTE SERVICE", "Value: " + mServers[i]);
      if (mServers[i] != null) {
        Log.i("-> REMOTE SERVICE", "Create Task for: " + mServers[i]);
        mRefreshedCounter++;
        new Task(mServers[i], 1337, i).start();

        //				try {
        //					Log.i("-> REMOTE SERVICE", "Next create address :" + servers[i]);
        //					InetAddress address = InetAddress.getByName(servers[i]);
        //					Log.i("-> REMOTE SERVICE", "Next isReachable? :" + servers[i]);
        //					if (address.isReachable(2000)){
        //						Log.i("-> REMOTE SERVICE", "Next isReachable = TRUE :" + servers[i]);
        //						new Task(servers[i],1337 ,i).start();
        //					}
        //				} catch (UnknownHostException e) {
        //					// TODO Auto-generated catch block
        //					mValues[i] = servers[i] + ";false";
        //					e.printStackTrace();
        //				} catch (IOException e) {
        //					// TODO Auto-generated catch block
        //					mValues[i] = servers[i] + ";false";
        //					e.printStackTrace();
        //				}
      }
    }

    //		mThread = new Task();
    //		mThread.isDone = false;
    //		mThread.start();

  }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "onStartCommand");

    // @TODO should test if startCommand is from autolaunch on boot -> then if yes, check if
    // CordovaStepCounter.ACTION_START has really been called or die
    Log.i(TAG, "- Relaunch service in 1 hour (4.4.2 start_sticky bug ) : ");
    Intent newServiceIntent = new Intent(this, StepCounterService.class);
    AlarmManager aManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent stepIntent =
        PendingIntent.getService(
            getApplicationContext(), 10, newServiceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    // PendingIntent.GetService (ApplicationContext, 10, intent2, PendingIntentFlags.UpdateCurrent);

    aManager.set(
        AlarmManager.RTC, java.lang.System.currentTimeMillis() + 1000 * 60 * 60, stepIntent);

    if (isRunning /* || has no step sensors */) {
      Log.i(TAG, "Not initialising sensors");
      return Service.START_STICKY;
    }

    Log.i(TAG, "Initialising sensors");
    doInit();

    isRunning = true;
    return Service.START_STICKY;
  }
  /**
   * Same as download but the image is always downloaded and the cache is not used. Kept private at
   * the moment as its interest is not clear.
   */
  private void forceDownload(String url, ImageView imageView) {
    // State sanity: url is guaranteed to never be null in DownloadedDrawable and cache keys.
    if (url == null) {
      Log.i("imageUp", "URL이 널");
      imageView.setImageDrawable(null);
      return;
    }

    if (cancelPotentialDownload(url, imageView)) {
      switch (mode) {
        case NO_ASYNC_TASK:
          Log.i("imageUp", "NO_ASYNC_TASK");
          Bitmap bitmap = downloadBitmap(url);
          addBitmapToCache(url, bitmap);
          imageView.setImageBitmap(bitmap);
          break;

        case NO_DOWNLOADED_DRAWABLE:
          Log.i("imageUp", "NO_DOWNLOADED_DRAWABLE");
          imageView.setMinimumHeight(156);
          BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
          task.execute(url);
          break;

        case CORRECT:
          Log.i("imageUp", "CORRECT");
          task = new BitmapDownloaderTask(imageView);
          DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
          imageView.setImageDrawable(downloadedDrawable);
          imageView.setMinimumHeight(156);
          task.execute(url);
          break;
      }
    }
  }
 /**
  * 鍦ㄤ細璇濆垪琛ㄤ腑鎺ユ敹娑堟伅
  *
  * @param event
  */
 public void onEventMainThread(MessageEvent event) {
   Log.i(TAG, "onEventMainThread MessageEvent execute");
   Message msg = event.getMessage();
   String targetID = msg.getTargetID();
   ConversationType convType = msg.getTargetType();
   Conversation conv;
   if (convType == ConversationType.group) {
     conv = JMessageClient.getGroupConversation(Integer.parseInt(targetID));
   } else {
     conv = JMessageClient.getSingleConversation(targetID);
   }
   if (conv != null && convType == ConversationType.single) {
     // 濡傛灉缂撳瓨浜嗗ご鍍忥紝鐩存帴鍒锋柊浼氳瘽鍒楄〃
     if (NativeImageLoader.getInstance().getBitmapFromMemCache(targetID) != null) {
       Log.i("Test", "conversation ");
       mConvListController.refreshConvList();
       // 娌℃湁澶村儚锛屼粠Conversation鎷�
     } else {
       File file = conv.getAvatarFile();
       // 鎷垮埌鍚庣紦瀛樺苟鍒锋柊
       if (file != null) {
         mConvListController.loadAvatarAndRefresh(targetID, file.getAbsolutePath());
         // conversation涓病鏈夊ご鍍忥紝鐩存帴鍒锋柊锛孲DK浼氬湪鍚庡彴鑾峰緱澶村儚锛屾嬁鍒板悗浼氭墽琛宱nEvent(ConversationRefreshEvent
         // conversationRefreshEvent)
       } else mConvListController.refreshConvList();
     }
   } else {
     mConvListController.refreshConvList();
   }
 }
Example #15
0
        public void onGpsStatusChanged(int event) {
          switch (event) {
              // 第一次定位
            case GpsStatus.GPS_EVENT_FIRST_FIX:
              Log.i(TAG, "第一次定位");
              break;
              // 卫星状态改变
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
              Log.i(TAG, "卫星状态改变");
              // 获取当前状态

              GpsStatus gpsStatus = lm.getGpsStatus(null);
              // 获取卫星颗数的默认最大值
              int maxSatellites = gpsStatus.getMaxSatellites();

              System.out.println("搜索到:" + maxSatellites + "颗卫星");
              break;
              // 定位启动
            case GpsStatus.GPS_EVENT_STARTED:
              // Log.i(TAG, "定位启动");
              break;
              // 定位结束
            case GpsStatus.GPS_EVENT_STOPPED:
              break;
          }
        };
 @Override
 public void onReceive(Context context, Intent intent) {
   // Log.v(TAG, "Receiving: " + intent.getAction());
   if (intent.getAction().equals(OppProbe.getStatusAction(probeName))) {
     OppProbe.Status status = new OppProbe.Status(intent.getExtras());
     if (probeName.equals(status.getName())) {
       Log.i(TAG, "Is a status action for " + probeName);
       long nonce = intent.getLongExtra(OppProbe.ReservedParamaters.NONCE.name, 0L);
       Log.i(TAG, "Nonce is " + nonce + "'");
       if (!sent && nonce != 0L) {
         sent = true;
         expirationTimer.cancel();
         try {
           context.unregisterReceiver(DataResponder.this);
         } catch (IllegalArgumentException e) {
           // already removed;
         }
         final Intent i = new Intent(OppProbe.getGetAction(probeName));
         Log.i(TAG, "Sending intent '" + i.getAction() + "'");
         i.setPackage(context.getPackageName()); // Send only to this app for right now
         i.putExtra(OppProbe.ReservedParamaters.PACKAGE.name, context.getPackageName());
         if (requestId != null && !"".equals(requestId)) {
           i.putExtra(OppProbe.ReservedParamaters.REQUEST_ID.name, requestId);
         }
         i.putExtra(OppProbe.ReservedParamaters.REQUESTS.name, requests);
         i.putExtra(OppProbe.ReservedParamaters.NONCE.name, nonce);
         context.sendBroadcast(i);
       }
     }
   }
 }
    /**
     * Helper method to get the contents of the visitor message, save the image, and save the event
     *
     * @param msg
     */
    private void saveVisitor(StateDeviceProtos.StateDeviceMessage msg) {
      Log.i(TAG, "Logging Event");
      Visitor visitor = new Visitor();
      Long time = System.currentTimeMillis();
      ByteString data = msg.getData();
      String filename = "visitor" + System.currentTimeMillis() + ".jpg";
      visitor.setImagePath(filename);
      File imageDirectory = new File(mContext.getFilesDir() + ConstantManager.IMAGE_DIR);

      // create the image directory if it doesn't exist
      if (!imageDirectory.exists()) {
        Log.i(TAG, "Directory being created? " + imageDirectory.mkdirs());
      }

      // save the image file
      File image = new File(imageDirectory, filename);
      try {
        if (!image.exists()) {
          Log.i(TAG, "File being created? " + image.createNewFile());
        }
        FileOutputStream fos = new FileOutputStream(image, true);
        fos.write(data.toByteArray());
        fos.close();
      } catch (IOException e) {
        e.printStackTrace();
      }

      // Log the visitor
      visitor.setTime(time);
      visitor.setLocation(msg.getName());
      VisitorLog.logVisitor(visitor, mContext);
    }
  @Override
  public void onReceive(Context context, Intent intent) {
    if (Params.TAG_FG_DEBUG && fgDebugLocal) {
      Log.i(Params.TAG_GEN, TAG_LOCAL + "notificationCatcherReceiver - Received message");
    }
    ;
    if (Params.TAG_FG_DEBUG && fgDebugLocal) {
      Log.i(
          Params.TAG_GEN,
          TAG_LOCAL + "notificationCatcherReceiver - intent.getAction() :: " + intent.getAction());
    }
    ;
    if (Params.TAG_FG_DEBUG && fgDebugLocal) {
      Log.i(
          Params.TAG_GEN,
          TAG_LOCAL
              + "notificationCatcherReceiver - EXTRA_PACKAGE) :: "
              + intent.getStringExtra(SendNotificationService.EXTRA_PACKAGE));
    }
    ;
    if (Params.TAG_FG_DEBUG && fgDebugLocal) {
      Log.i(
          Params.TAG_GEN,
          TAG_LOCAL
              + "notificationCatcherReceiver - EXTRA_MESSAGE) :: "
              + intent.getStringExtra(SendNotificationService.EXTRA_MESSAGE));
    }
    ;

    intent = new Intent(context, SendNotification.class);
    intent.putExtra("notification", message);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
  }
    @Override
    public void onMessageReceived(StateDeviceProtos.StateDeviceMessage msg) {
      if (msg != null && msg.getType() == StateDeviceProtos.StateDeviceMessage.Type.DOORBELL) {

        Log.i(TAG, "New message received");

        // create a device from the message
        StateDevice device = new StateDevice(msg);

        if (StateDeviceManager.contains(msg.getId())) {
          // update the device
          StateDeviceManager.updateStateDevice(device);
        } else {
          // add the device
          StateDeviceManager.addStateDevice(device);
        }

        // notification and save image
        if (msg.getType() == StateDeviceProtos.StateDeviceMessage.Type.DOORBELL) {
          if (msg.hasData()) {
            Notifications.sendDoorbellAlertNotification(mContext, msg);
            saveVisitor(msg);
          } else {
            Log.i(TAG, msg.toString());
          }
        }
      }
    }
  /** We have received a push notification from GCM, analyze the intents bundle for the payload. */
  @Override
  protected void onMessage(Context context, Intent intent) {

    Log.i(TAG, "Received message");
    displayMessage(context, "Message Received");
    String message = null;
    String title = null;
    String url = null;

    if (intent != null) {

      // Check the bundle for the pay load body and title
      Bundle bundle = intent.getExtras();
      if (bundle != null) {
        displayMessage(context, "Message bundle: " + bundle);

        Log.i(TAG, "Message bundle: " + bundle);
        message = bundle.getString("message");

        title = bundle.getString("title");

        url = bundle.getString("url");
      }
    }
    // If there was no body just use a standard message
    if (message == null) {
      message = getString(R.string.airbop_message);
    }

    generateNotification(context, title, message, url);
  }
  /**
   * Launch the SipCallOptionHandler, which is the next step(*) in the outgoing-call sequence after
   * the outgoing call broadcast is complete.
   *
   * <p>(*) We now know exactly what phone number we need to dial, so the next step is for the
   * SipCallOptionHandler to decide which Phone type (SIP or PSTN) should be used. (Depending on the
   * user's preferences, this decision may also involve popping up a dialog to ask the user to
   * choose what type of call this should be.)
   *
   * @param context used for the startActivity() call
   * @param intent the intent from the previous step of the outgoing-call sequence. Normally this
   *     will be the NEW_OUTGOING_CALL broadcast intent that came in to the OutgoingCallReceiver,
   *     although it can also be the original ACTION_CALL intent that started the whole sequence (in
   *     cases where we don't do the NEW_OUTGOING_CALL broadcast at all, like for emergency numbers
   *     or SIP addresses).
   * @param uri the data URI from the original CALL intent, presumably either a tel: or sip: URI.
   *     For tel: URIs, note that the scheme-specific part does *not* necessarily have separators
   *     and keypad letters stripped (so we might see URIs like "tel:(650)%20555-1234" or
   *     "tel:1-800-GOOG-411" here.)
   * @param number the actual number (or SIP address) to dial. This is guaranteed to be either a
   *     PSTN phone number with separators stripped out and keypad letters converted to digits (like
   *     "16505551234"), or a raw SIP address (like "[email protected]").
   */
  private void startSipCallOptionHandler(Context context, Intent intent, Uri uri, String number) {
    if (VDBG) {
      Log.i(TAG, "startSipCallOptionHandler...");
      Log.i(TAG, "- intent: " + intent);
      Log.i(TAG, "- uri: " + uri);
      Log.i(TAG, "- number: " + number);
    }

    // Create a copy of the original CALL intent that started the whole
    // outgoing-call sequence.  This intent will ultimately be passed to
    // CallController.placeCall() after the SipCallOptionHandler step.

    Intent newIntent = new Intent(Intent.ACTION_CALL, uri);
    newIntent.putExtra(EXTRA_ACTUAL_NUMBER_TO_DIAL, number);
    newIntent.putExtra(SUBSCRIPTION_KEY, mSubscription);
    PhoneUtils.checkAndCopyPhoneProviderExtras(intent, newIntent);

    // Finally, launch the SipCallOptionHandler, with the copy of the
    // original CALL intent stashed away in the EXTRA_NEW_CALL_INTENT
    // extra.

    Intent selectPhoneIntent = new Intent(ACTION_SIP_SELECT_PHONE, uri);
    selectPhoneIntent.setClass(context, SipCallOptionHandler.class);
    selectPhoneIntent.putExtra(EXTRA_NEW_CALL_INTENT, newIntent);
    selectPhoneIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (DBG)
      Log.v(TAG, "startSipCallOptionHandler(): " + "calling startActivity: " + selectPhoneIntent);
    context.startActivity(selectPhoneIntent);
    // ...and see SipCallOptionHandler.onCreate() for the next step of the sequence.
  }
  @Override
  public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    // ...
    // Do plugin specifics.
    // ...
    Log.i(PluginConstants.LOG_TAG, "Starting Service...");
    Log.i(PluginConstants.LOG_TAG, "Starting Service...");

    startWork();
    Log.i(LOG_TAG, "after startWork()");

    new Handler()
        .postAtTime(
            new Runnable() {

              @Override
              public void run() {
                Log.i(LOG_TAG, "run() called");
                sendShoppingItem(mPos);
              }
            },
            System.currentTimeMillis() + 1000
            /** 60 * 2 */
            );
  }
Example #23
0
 protected void handleImage(List<AdInfo> adinfos) {
   DisplayImageOptions options;
   if (UtilsTools.hasDiskCache()) {
     options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
   } else {
     options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(false).build();
   }
   Log.i(TAG, "source infos size : " + adinfos.size());
   for (AdInfo adinfo : adinfos) {
     Log.i(TAG, "source url : " + adinfo.getPic_url());
     changeImagePos(adinfo);
     ImageSize targetSize =
         new ImageSize(
             mContext.getResources().getInteger(R.integer.ad_target_image_width),
             mContext.getResources().getInteger(R.integer.ad_target_image_height));
     final int t = adinfo.getDismiss_time();
     ImageLoader.getInstance()
         .loadImage(
             adinfo.getPic_url(),
             targetSize,
             options,
             new SimpleImageLoadingListener() {
               @Override
               public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                 mAdView.setImageBitmap(loadedImage);
                 mRefreshHandler.removeMessages(DISMISS_AD);
                 mRefreshHandler.sendEmptyMessageDelayed(DISMISS_AD, t);
                 if (mB != null && loadedImage != mB) {
                   mB.recycle();
                 }
                 mB = loadedImage;
               }
             });
   }
 }
  @Override
  public boolean onTouchEvent(MotionEvent event) {

    int y = (int) event.getRawY(); // 得到手势焦点相对于屏幕而言的Y轴坐标

    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN: // 手势落下的时候回调
        Log.i(TAG, "ACTION_DOWN");
        // 记录下y坐标
        lastY = y;
        break;

      case MotionEvent.ACTION_MOVE: // 移动时回掉
        Log.i(TAG, "ACTION_MOVE");
        // y移动坐标
        int m = y - lastY; // 如果在移动距离大于-1小于6时,判断为需要执行滑动
        if (((m < 6) && (m > -1)) || (!isDragging)) {
          setLastRefreshTimeText();
          doMovement(m);
        }
        // 记录下此刻y坐标
        this.lastY = y;
        break;

      case MotionEvent.ACTION_UP:
        Log.i(TAG, "ACTION_UP");

        fling();

        break;
    }
    return true;
  }
  /** Opens a rear-facing camera with {@link Camera#open(int)}, if one exists, or opens camera 0. */
  public static Camera open() {

    int numCameras = Camera.getNumberOfCameras();
    if (numCameras == 0) {
      Log.w(TAG, "No cameras!");
      return null;
    }

    int index = 0;
    while (index < numCameras) {
      Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
      Camera.getCameraInfo(index, cameraInfo);
      // CAMERA_FACING_BACK:手机背面的摄像头
      if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
        break;
      }
      index++;
    }

    Camera camera;
    if (index < numCameras) {
      Log.i(TAG, "Opening camera #" + index);
      camera = Camera.open(index);
    } else {
      Log.i(TAG, "No camera facing back; returning camera #0");
      camera = Camera.open(0);
    }

    return camera;
  }
Example #26
0
  private void processOfflineMessages() {
    Log.i(LOG_TAG, "Begin retrieval of offline messages from server");

    OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con);
    try {
      if (!offlineMessageManager.supportsFlexibleRetrieval()) {
        Log.d(LOG_TAG, "Offline messages not supported");
        return;
      }

      List<Message> msgs = offlineMessageManager.getMessages();
      for (Message msg : msgs) {
        Intent intent =
            new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
        intent.putExtra(
            MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom()));
        intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody());

        context.startService(intent);
      }

      offlineMessageManager.deleteMessages();
    } catch (Exception e) {
      Log.e(LOG_TAG, "handle offline messages error ", e);
    }

    Log.i(LOG_TAG, "End of retrieval of offline messages from server");
  }
 public static void setBestExposure(Camera.Parameters parameters, boolean lightOn) {
   int minExposure = parameters.getMinExposureCompensation();
   int maxExposure = parameters.getMaxExposureCompensation();
   float step = parameters.getExposureCompensationStep();
   if ((minExposure != 0 || maxExposure != 0) && step > 0.0f) {
     // Set low when light is on
     float targetCompensation = lightOn ? MIN_EXPOSURE_COMPENSATION : MAX_EXPOSURE_COMPENSATION;
     int compensationSteps = Math.round(targetCompensation / step);
     float actualCompensation = step * compensationSteps;
     // Clamp value:
     compensationSteps = Math.max(Math.min(compensationSteps, maxExposure), minExposure);
     if (parameters.getExposureCompensation() == compensationSteps) {
       Log.i(
           TAG,
           "Exposure compensation already set to "
               + compensationSteps
               + " / "
               + actualCompensation);
     } else {
       Log.i(
           TAG,
           "Setting exposure compensation to " + compensationSteps + " / " + actualCompensation);
       parameters.setExposureCompensation(compensationSteps);
     }
   } else {
     Log.i(TAG, "Camera does not support exposure compensation");
   }
 }
Example #28
0
  private void stopTreatment() {
    // send 0V command
    sendDataToDevice(EbandageGattAttributes.ZERO_VOLTS);
    voltageTextView.setText("");
    polarityTextView.setText("");
    max_volt = false; // default state
    polarityChanged = false; // default state POSITIVE
    timerStopped = true; // default timer stopped state
    // set button default state
    showMinutes(true);
    setButtonDisabled(true);
    increaseThread = null;
    decreaseThread = null;
    countDownTimer.cancel();

    // send OFF command to device
    if (mBluetoothLeService.sendPolarityCharacteristics(
        hexStringToByteArray(EbandageGattAttributes.EBANDAGE_OFF))) {
      Log.i(TAG, "Device is turned off");
    } else {
      Log.i(TAG, "Turning device off failed");
      // Try again !
      mBluetoothLeService.sendPolarityCharacteristics(
          hexStringToByteArray(EbandageGattAttributes.EBANDAGE_OFF));
    }
  }
Example #29
0
 private void changePolarity() {
   // change polarity to negative
   boolean polarity =
       mBluetoothLeService.sendPolarityCharacteristics(
           hexStringToByteArray(EbandageGattAttributes.EBANDAGE_NEGATIVE));
   if (polarity) {
     Log.i(TAG, "Polarity changed");
     polarityChanged = true;
     Thread thread =
         new Thread(
             new Runnable() {
               @Override
               public void run() {
                 try {
                   // 1 seconds delay
                   Thread.sleep(1);
                   // send negative volt to device
                   changeVolt();
                 } catch (InterruptedException e) {
                   e.printStackTrace();
                 }
               }
             });
     thread.start();
   } else {
     Log.i(TAG, "Changing polarity failed");
     mBluetoothLeService.sendPolarityCharacteristics(
         hexStringToByteArray(EbandageGattAttributes.EBANDAGE_NEGATIVE));
   }
 }
  public ArrayList<Info> getInfo() {
    cursor = musicBase.query("mytable", null, null, null, null, null, null);

    initColumns();

    ArrayList<Info> list = new ArrayList<>();
    if (cursor.moveToFirst()) {

      do {
        Info addedInfo =
            new Info(
                cursor.getString(nameCollumIndex),
                cursor.getInt(durationCollumIndex),
                new User(cursor.getString(authorCollumIndex)),
                cursor.getInt(likesCountCollumIndex),
                cursor.getString(streamUrlCollumIndex),
                cursor.getString(pathToFileCollumIndex),
                cursor.getString(artworkUrlCollumIndex));
        list.add(addedInfo);
        Log.i("list", addedInfo.toString());
        Log.i("list", "----------------------------------------------");
      } while (cursor.moveToNext());
    }
    return list;
  }