Пример #1
1
  public void download(String url, String fileName) {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
      Uri uri = Uri.parse(url);

      DownloadManager.Request r = new DownloadManager.Request(uri);
      r.setAllowedNetworkTypes(Request.NETWORK_WIFI);
      r.setAllowedOverRoaming(false);

      // set mime type
      MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
      String mimeType =
          mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
      r.setMimeType(mimeType);

      // set in notification
      r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
      r.setVisibleInDownloadsUi(true);

      // sdcard
      if (TextUtils.isEmpty(fileName)) fileName = uri.getLastPathSegment();
      r.setDestinationInExternalFilesDir(mContext, File.separator, fileName);
      r.setTitle(fileName);

      // start download
      mDownloadId = mDM.enqueue(r);
    } else if (mListener != null) {
      SystemClock.sleep(1000);
      mListener.onDownloadComplete(null);
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SystemClock.sleep(2000);

    // Check network connection
    if (!Commons.isNetworkAvailable(getApplicationContext())) {
      SystemClock.sleep(1500);
      Commons.showToastMessage("No internet connection", getApplicationContext());
      nextActivityAfterLogin(MainActivity.class);
      return;
    }

    // Check if there is already an authorisation for firebase which the user application have
    // logged in previously
    Firebase fbRef = new Firebase(Constants.FIREBASE_MAIN);
    SharedPreferences prefs;
    // if there is valid authorisation, redirect to next activity
    if (fbRef.getAuth() != null) {
      prefs = getSharedPreferences(Constants.SHARE_PREF_LINK, MODE_PRIVATE);
      String role = prefs.getString(Constants.SHAREPREF_ROLE, null);
      String phoneNo = prefs.getString(Constants.SHAREPREF_PHONE_NO, null);
      if (phoneNo == null || role == null) {
        fbRef.unauth();
        nextActivityAfterLogin(MainActivity.class);
      } else retrieveAccountInfo(phoneNo, role);
    } else {
      nextActivityAfterLogin(MainActivity.class);
    }
  }
  public void testSessions() {
    Context context = activity.getApplicationContext();

    // starting from a clean slate
    mockLogger.test(
        "Was AdjustActivityState deleted? " + ActivityHandler.deleteActivityState(context));

    // adjust the intervals for testing
    AdjustFactory.setSessionInterval(2000);
    AdjustFactory.setSubsessionInterval(100);

    ActivityHandler activityHandler = new ActivityHandler(activity);

    // start the first session
    activityHandler.trackSubsessionStart();

    // wait enough to be a new subsession, but not a new session
    SystemClock.sleep(1500);

    activityHandler.trackSubsessionStart();
    // wait enough to be a new session
    SystemClock.sleep(4000);
    activityHandler.trackSubsessionStart();
    // test the subsession end
    activityHandler.trackSubsessionEnd();
    SystemClock.sleep(1000);

    // check that a new subsession was created
    assertTrue(
        mockLogger.toString(),
        mockLogger.containsMessage(LogLevel.INFO, "Started subsession 2 of session 1"));

    // check that it's now on the 2nd session
    assertTrue(mockLogger.toString(), mockLogger.containsMessage(LogLevel.DEBUG, "Session 2"));

    // check that 2 packages were added to the package handler
    assertEquals(2, mockPackageHandler.queue.size());

    // get the second session package and its parameters
    ActivityPackage activityPackage = mockPackageHandler.queue.get(1);
    Map<String, String> parameters = activityPackage.getParameters();

    // the session and subsession count should be 2
    assertEquals(
        activityPackage.getExtendedString(), 2, Integer.parseInt(parameters.get("session_count")));
    assertEquals(
        activityPackage.getExtendedString(),
        2,
        Integer.parseInt(parameters.get("subsession_count")));

    // TODO test updated timeSpent and sessionLenght
    mockLogger.test("timeSpent " + parameters.get("time_spent"));
    mockLogger.test("sessionLength " + parameters.get("session_length"));

    // check that the package handler was paused
    assertTrue(
        mockLogger.toString(), mockLogger.containsTestMessage("PackageHandler pauseSending"));
  }
Пример #4
0
  /**
   * Create tombstones for the list of processes.
   *
   * @param ProcList The list of processes with ',' as a delimiter.
   */
  private void createTombstone(String procList) {
    String cmd = "ps";
    List<String> procList4Tombstones = new ArrayList<String>();
    String line;

    StringBuffer sb = new StringBuffer();
    sb.append(",");
    sb.append(procList);
    sb.append(",");
    procList = sb.toString();

    try {
      java.lang.Process p = Runtime.getRuntime().exec(cmd);
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      while ((line = input.readLine()) != null) {
        String[] tokens = line.split("\\s+");
        if (tokens.length == 9) {
          String delimiter1 = "/";
          String[] procname = tokens[8].split(delimiter1);
          StringBuffer sb1 = new StringBuffer();
          sb1.append(",");
          sb1.append(procname[procname.length - 1]);
          sb1.append(",");
          String pn = sb1.toString();
          if (procList.indexOf(pn) >= 0) {
            procList4Tombstones.add(tokens[1]);
            procList4Tombstones.add(procname[procname.length - 1]);
          }
        }
      }
      input.close();
    } catch (Exception ex) {
      Slog.w(TAG, ex);
    }

    Iterator<String> it = procList4Tombstones.iterator();
    while (it.hasNext()) {
      /*
       * Sometimes the debuggerd will exit after the tombstones creation which
       * will not allow the next tombstones generation.
       * Wait till the debuggerd is back.
       */
      Slog.w(TAG, "Waiting for the debuggerd process...");
      while (false == isProcessAlive("debuggerd")) {
        SystemClock.sleep(500);
      }
      String pid = it.next();
      Slog.w(TAG, "Creating tombstone file for process[" + it.next() + "]");
      SystemClock.sleep(1000);
      Process.sendSignal(Integer.parseInt(pid), 6);
      SystemClock.sleep(1000);
      Process.sendSignal(Integer.parseInt(pid), 6);
      SystemClock.sleep(2000);
    }
  }
 @Test
 public void checkShotsOpen() {
   for (int i = 0; i < Config.SHOTS_PER_PAGE + 1; i++) {
     onView(allOf(withId(R.id.rvShots), isDisplayed()))
         .perform(
             RecyclerViewActions.scrollToPosition(i),
             RecyclerViewActions.actionOnItemAtPosition(i, click()));
     sleep(2000);
     pressBack();
     sleep(2000);
   }
 }
Пример #6
0
  @Override
  protected void runInBackground() {
    mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
    Log.d(TAG, "Usb manager: " + mUsbManager);
    if (mUsbManager == null) {
      Log.e(TAG, "No USB manager, exiting.");
      return;
    }

    Log.d(TAG, "Main loop running.");

    try {
      while (true) {
        switch (mState) {
          case IDLE:
            if (acquireSerialDevice()) {
              Log.d(TAG, "Serial device found, switching to running!");
              stateChange(State.RUNNING);
              tryPing();
            } else {
              Log.d(TAG, "Waiting for serial device.");
              SystemClock.sleep(IDLE_POLL_INTERVAL_MILLIS);
            }
            break;
          case RUNNING:
            serviceSerialDevice();
            break;
          case STOPPING:
            releaseSerialDevice();
            SystemClock.sleep(IDLE_POLL_INTERVAL_MILLIS);
            stateChange(State.IDLE);
            break;
          case FINISHED:
            releaseSerialDevice();
            return;
          default:
            Log.wtf(TAG, "Unknown state: " + mState);
            return;
        }
        if (Thread.currentThread().isInterrupted()) {
          Log.w(TAG, "Thread interrupted, exiting.");
          break;
        }
      }
    } finally {
      Log.d(TAG, "Main loop exiting.");
    }
  }
Пример #7
0
 @Override
 protected Void doInBackground(Void... params) {
   if (!isCancelled() && isCancle == false) {
     int pro = 0;
     while (pro < 101) {
       if (pro < 70 && (pro > 0 || pro == 0)) {
         SystemClock.sleep(100);
       } else {
         SystemClock.sleep(800);
       }
       publishProgress(pro);
       pro++;
     }
   }
   return null;
 }
Пример #8
0
 protected Result onPostExecute(Result result) {
   SystemClock.sleep(
       6500); // I am not sure of a better way to stop the UI from beating the data in, if you
              // have any tips I would appreciate them. I should use the on finish method from
              // the Async task, will implement if there is more time
   return null;
 }
Пример #9
0
    @Override
    protected String doInBackground(String... params) {

      int lenght = urls.size();
      int numa = 0;
      // loop view
      while (i < lenght) {
        // put index image,num of ani
        publishProgress(String.valueOf(i), String.valueOf(numa));
        /** check stop */
        if (pressBack == true || autoPlayState == false) {
          break;
        }
        SystemClock.sleep(4000);
        // if finish restart from 0
        if (i == lenght - 1) {
          i = 0;
        }
        // set animation number
        if (numa < anim.size() - 1) {
          numa++;
        } else {
          i++;
          numa = 0;
        }
      }
      return null;
    }
  @SmallTest
  @Feature({"IntentHandling"})
  public void testIntentHavingChromePackageName() {
    TabRedirectHandler handler = new TabRedirectHandler(mContext);
    Intent fooIntent = new Intent(sFooIntent);
    fooIntent.setPackage(TEST_PACKAGE_NAME);
    handler.updateIntent(fooIntent);
    assertFalse(handler.isOnNavigation());
    assertTrue(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    handler.updateNewUrlLoading(TRANS_TYPE_OF_LINK_FROM_INTENT, false, false, 0, 0);
    assertTrue(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));
    handler.updateNewUrlLoading(PageTransition.LINK, false, false, 0, 1);
    assertTrue(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    assertTrue(handler.isOnNavigation());
    assertEquals(0, handler.getLastCommittedEntryIndexBeforeStartingNavigation());

    SystemClock.sleep(1);
    handler.updateNewUrlLoading(PageTransition.LINK, false, true, SystemClock.elapsedRealtime(), 2);
    assertFalse(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    assertTrue(handler.isOnNavigation());
    assertEquals(2, handler.getLastCommittedEntryIndexBeforeStartingNavigation());
  }
Пример #11
0
  @Override
  public boolean retryRequest(IOException e, int executionCount, HttpContext context) {
    boolean retry = true;

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b);

    if (executionCount > maxRetries) {
      retry = false;
    } else if (isInList(exceptionWhiteList, e)) {
      retry = true;
    } else if (isInList(exceptionBlackList, e)) {
      retry = false;
    } else if (!sent) {
      retry = true;
    }

    if (retry) {
      HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
      if (request == null) {
        return false;
      }
    }

    if (retry) {
      SystemClock.sleep(retrySleepTimeMS);
    } else {
      e.printStackTrace();
    }

    return retry;
  }
  // TODO: we could probably improve performance by re-using connections instead of closing them
  // after each and every download
  protected Bitmap downloadImage() {
    int timesTried = 1;

    while (timesTried <= numRetries) {
      try {
        byte[] imageData = retrieveImageData();

        if (imageData == null) {
          break;
        }

        if (imageCache != null) {
          imageCache.put(imageUrl, imageData);
        }

        return BitmapFactory.decodeByteArray(imageData, 0, imageData.length);

      } catch (Throwable e) {
        Log.w(LOG_TAG, "download for " + imageUrl + " failed (attempt " + timesTried + ")");
        e.printStackTrace();
        SystemClock.sleep(DEFAULT_RETRY_HANDLER_SLEEP_TIME);
        timesTried++;
      }
    }

    return null;
  }
  private Bitmap decodeWithOOMHandling(URI imageUri) throws IOException {
    Bitmap result = null;
    ImageDecoder decoder = new ImageDecoder(imageUri, downloader, options);
    decoder.setLoggingEnabled(loggingEnabled);
    for (int attempt = 1; attempt <= ATTEMPT_COUNT_TO_DECODE_BITMAP; attempt++) {
      try {
        ViewScaleType viewScaleType = ViewScaleType.fromImageView(imageView);
        result = decoder.decode(targetSize, options.getImageScaleType(), viewScaleType);
      } catch (OutOfMemoryError e) {
        L.e(e);

        switch (attempt) {
          case 1:
            System.gc();
            break;
          case 2:
            configuration.memoryCache.clear();
            System.gc();
            break;
          case 3:
            throw e;
        }
        // Wait some time while GC is working
        SystemClock.sleep(attempt * 1000);
        continue;
      }
      break;
    }
    return result;
  }
  @SmallTest
  @Feature({"IntentHandling"})
  public void testNavigationWithForwardBack() {
    TabRedirectHandler handler = new TabRedirectHandler(mContext);
    handler.updateIntent(sYtIntent);
    assertFalse(handler.isOnNavigation());
    assertFalse(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    handler.updateNewUrlLoading(
        PageTransition.FORM_SUBMIT | PageTransition.FORWARD_BACK,
        false,
        true,
        SystemClock.elapsedRealtime(),
        0);
    assertTrue(handler.shouldStayInChrome(false));
    assertTrue(handler.shouldStayInChrome(true));
    handler.updateNewUrlLoading(
        PageTransition.LINK, false, false, SystemClock.elapsedRealtime(), 1);
    assertTrue(handler.shouldStayInChrome(false));
    assertTrue(handler.shouldStayInChrome(true));

    assertTrue(handler.isOnNavigation());
    assertEquals(0, handler.getLastCommittedEntryIndexBeforeStartingNavigation());

    SystemClock.sleep(1);
    handler.updateNewUrlLoading(PageTransition.LINK, false, true, SystemClock.elapsedRealtime(), 2);
    assertFalse(handler.shouldStayInChrome(false));
    assertFalse(handler.shouldStayInChrome(true));

    assertTrue(handler.isOnNavigation());
    assertEquals(2, handler.getLastCommittedEntryIndexBeforeStartingNavigation());
  }
Пример #15
0
  /*
   * UiAutomator has a broken longClick. getAutomatorBridge is private so we
   * access the bridge via reflection to use the touchDown / touchUp methods.
   */
  private boolean correctLongClick(final int x, final int y, final int duration) {
    try {
      /*
       * bridge.getClass() returns ShellUiAutomatorBridge on API 18/19 so use
       * the super class.
       */

      final UiDevice device = UiDevice.getInstance();
      final Object bridge = enableField(device.getClass(), "mUiAutomationBridge").get(device);
      final Object controller =
          enableField(bridge.getClass().getSuperclass(), "mInteractionController").get(bridge);
      final Class<?> controllerClass = controller.getClass();

      Logger.debug("Finding methods on class: " + controllerClass);
      final Method touchDown = controllerClass.getDeclaredMethod("touchDown", int.class, int.class);
      touchDown.setAccessible(true);
      final Method touchUp = controllerClass.getDeclaredMethod("touchUp", int.class, int.class);
      touchUp.setAccessible(true);

      if ((Boolean) touchDown.invoke(controller, x, y)) {
        SystemClock.sleep(duration);
        if ((Boolean) touchUp.invoke(controller, x, y)) {
          return true;
        }
      }
      return false;

    } catch (final Exception e) {
      Logger.debug("Problem invoking correct long click: " + e);
      return false;
    }
  }
Пример #16
0
  @Override
  public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    boolean retry = true;

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b.booleanValue());

    if (executionCount > maxRetries) {
      // 尝试次数超过用户定义的测试,默认5次
      retry = false;
    } else if (exceptionBlacklist.contains(exception.getClass())) {
      // 线程被用户中断,则不继续尝试
      retry = false;
    } else if (exceptionWhitelist.contains(exception.getClass())) {
      retry = true;
    } else if (!sent) {
      retry = true;
    }

    if (retry) {
      HttpUriRequest currentReq =
          (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
      retry = currentReq != null && !"POST".equals(currentReq.getMethod());
    }

    if (retry) {
      // 休眠1秒钟后再继续尝试
      SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
    } else {
      exception.printStackTrace();
    }

    return retry;
  }
Пример #17
0
  static int smsFixup(Context context) {
    int nr = 0;
    ContentValues values = new ContentValues(1);
    Log.d(TAG, "start fixup");
    values.put(reply_path_present, 0);

    ContentResolver contentResolver = context.getContentResolver();
    int retries = 3;
    while (retries > 0) {
      try {
        // throw new SQLiteException("failed");
        nr =
            contentResolver.update(
                Uri.parse("content://sms/inbox"), values, reply_path_present + "!=" + "0", null);
        retries = -1;
      } catch (SQLiteException e) {
        Log.d(TAG, "SQLiteException, retrying...");
        SystemClock.sleep(1000);
        retries--;
      }
    }
    if (retries == -1) Log.d(TAG, "end fixup, updated " + nr + " SMS");
    else Log.d(TAG, "end fixup, failed with SQLiteException");
    return nr;
  }
  @SmallTest
  @Feature({"IntentHandling"})
  public void testUserInteraction() {
    TabRedirectHandler handler = new TabRedirectHandler(mContext);
    handler.updateIntent(sYtIntent);
    assertFalse(handler.isOnNavigation());

    handler.updateNewUrlLoading(TRANS_TYPE_OF_LINK_FROM_INTENT, false, false, 0, 0);
    assertFalse(handler.isOnEffectiveIntentRedirectChain());
    handler.updateNewUrlLoading(TRANS_TYPE_OF_LINK_FROM_INTENT, true, false, 0, 0);
    assertTrue(handler.isOnEffectiveIntentRedirectChain());
    assertFalse(handler.hasNewResolver(sMoblieYtIntent));

    assertTrue(handler.isOnNavigation());
    assertEquals(0, handler.getLastCommittedEntryIndexBeforeStartingNavigation());

    SystemClock.sleep(1);
    handler.updateNewUrlLoading(PageTransition.LINK, false, true, SystemClock.elapsedRealtime(), 1);
    assertFalse(handler.isOnEffectiveIntentRedirectChain());
    assertTrue(handler.hasNewResolver(sMoblieYtIntent));
    assertTrue(handler.hasNewResolver(sFooIntent));
    assertFalse(handler.hasNewResolver(null));

    assertTrue(handler.isOnNavigation());
    assertEquals(1, handler.getLastCommittedEntryIndexBeforeStartingNavigation());
  }
Пример #19
0
  @Override
  protected void onHandleIntent(Intent intent) {
    NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(this);

    builder
        .setContent(buildContent(0))
        .setTicker(getText(R.string.ticker), buildTicker())
        .setContentIntent(buildContentIntent())
        .setLargeIcon(buildLargeIcon())
        .setSmallIcon(R.drawable.ic_stat_notif_small_icon)
        .setOngoing(true);

    Notification notif = builder.getNotification();

    for (int i = 0; i < 20; i++) {
      notif.contentView.setProgressBar(android.R.id.progress, 100, i * 5, false);
      mgr.notify(NOTIFICATION_ID, notif);

      if (i == 0) {
        notif.tickerText = null;
        notif.tickerView = null;
      }

      SystemClock.sleep(1000);
    }

    mgr.cancel(NOTIFICATION_ID);
  }
  public void registerForPush(
      Context context, String googleProjectNumber, PushRegistrator.RegisteredHandler callback) {
    lastCallback = callback;

    if (waitTimer > 0) SystemClock.sleep(waitTimer);

    callback.complete(fail ? null : regId);
  }
 @Override
 protected String doInBackground(Void... params) {
   while (!isCancelled()) {
     // 如果没有取消
     if (ComConnectivityManager.getInstance().isConnected()) {
       String device_token = UmengRegistrar.getRegistrationId(mContext);
       if (!TextUtils.isEmpty(device_token)) {
         DebugUtils.logD(TAG, "CheckDeviceTokenTask doInBackground() get " + device_token);
         return device_token;
       }
       SystemClock.sleep(5000); // sleep 5 s
     } else {
       SystemClock.sleep(60000); // sleep 60 s
     }
   }
   return null;
 }
Пример #22
0
    @Override
    protected String doInBackground(Void... params) {
      ArrayList<GestureStroke> strokes = mNeedAutoDrawGesture.getStrokes();
      mDrawPath = new Path();
      long sleepTime = getSleepTime(strokes);
      int strokesSize = strokes.size(); // 手势的笔画数
      for (int m = 0; m < strokesSize; m++) {
        if (mIsCanceledOneItem) {
          return null;
        }
        GestureStroke stroke = strokes.get(m);
        float[] points = stroke.points; // 笔画中路径坐标
        float mX = 0;
        float mY = 0;

        int pointsSize = points.length;

        for (int j = 0; j < pointsSize; j += 2) {
          if (mIsCanceledOneItem) {
            return null;
          }
          float x = points[j]; // X坐标
          float y = points[j + 1]; // Y坐标
          if (j == 0) {
            mDrawPath.moveTo(x, y);
            mX = x;
            mY = y;
          } else {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            // 判断2个点是否>一定值,如果设置过大会导致不圆滑
            if (dx >= mTOUCH_TOLERANCE || dy >= mTOUCH_TOLERANCE) {
              mDrawPath.lineTo(x, y);
              mX = x;
              mY = y;

              if (mIsCanceledOneItem) {
                return null;
              }
              synchronized (mLock) {
                publishProgress(mDrawPath);
                try {
                  SystemClock.sleep(sleepTime);
                  if (mIsCanceledOneItem) {
                    return null;
                  }
                  mLock.wait();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
              }
            }
          }
        }
      }

      return null;
    }
  @Override
  protected void onHandleIntent(Intent intent) {
    // processing done here�.

    // run forever
    while (true) {
      SystemClock.sleep(50);
    }
  }
 @Override
 protected ArrayList<Card> doInBackground(Void... params) {
   // elaborate images
   SystemClock.sleep(1000); // delay to simulate download, don't use it in a real app
   if (isAdded()) {
     ArrayList<Card> cards = initCard();
     return cards;
   } else return null;
 }
 @Test
 public void nullCommentHandling() {
   HashMap<String, String> map = new HashMap<>();
   map.put(
       FlickrURL.COMMENT_LIST, "{\"comments\":{\"photo_id\":\"21043155476\"},\"stat\":\"ok\"}");
   setupMockServer(map);
   activityRule.launchActivity(intent);
   SystemClock.sleep(3000);
   onView(withContentDescription("No Comment")).check(matches(withText(R.string.no_comment)));
 }
  /**
   * Create a contact. Delete it. And assert that the contact record is no longer present.
   *
   * @return The contact id and raw contact id that was created.
   */
  private DatabaseAsserts.ContactIdPair assertContactCreateDelete() {
    DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver);

    SystemClock.sleep(1);
    ContactUtil.delete(mResolver, ids.mContactId);

    assertFalse(ContactUtil.recordExistsForContactId(mResolver, ids.mContactId));

    return ids;
  }
 @Override
 public void run() {
   while (mAdbEnabled) {
     try {
       listenToSocket();
     } catch (Exception e) {
       /* Don't loop too fast if adbd dies, before init restarts it */
       SystemClock.sleep(1000);
     }
   }
 }
Пример #28
0
 public void onInit(int status) {
   Toast t = Toast.makeText(getApplicationContext(), A_dire, Toast.LENGTH_SHORT);
   t.show();
   mTts.speak(A_dire, TextToSpeech.QUEUE_FLUSH, null);
   if (last_init == false) {
     android.os.SystemClock.sleep(1000);
     startVoiceRecognitionCycle();
   } else {
     fin();
   }
 }
 private boolean waitForState(String state) {
   // wait for the transition to complete.
   // give up after 1 second.
   for (int i = 0; i < 20; i++) {
     // State transition is done when sys.usb.state is set to the new configuration
     if (state.equals(SystemProperties.get("sys.usb.state"))) return true;
     SystemClock.sleep(50);
   }
   Slog.e(TAG, "waitForState(" + state + ") FAILED");
   return false;
 }
Пример #30
0
  public void run() {

    while (true) {
      try {
        listenToSocket();
      } catch (Exception e) {
        Slog.e(TAG, "Error in NativeDaemonConnector", e);
        SystemClock.sleep(5000);
      }
    }
  }