@Override
  public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                anim2.end();
                anim1.start();
              }
            });
        break;
      case MotionEvent.ACTION_MOVE:
        break;
      case MotionEvent.ACTION_UP:
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                anim1.end();
                anim2.start();
                if (listener != null) {

                  listener.onClick(WinImageView.this);
                }
              }
            });
        // EventBus.getDefault().post(BusEvent.TYPE);
        break;
      case MotionEvent.ACTION_CANCEL:
        break;
    }
    return true;
  }
  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    mPositions.put(mDirectory.getAbsolutePath(), getListView().getFirstVisiblePosition());

    if (position < (mParent == null ? 0 : 1)) {
      mDirectory = mParent;
      mHandler.post(mUpdateFiles);
      return;
    }

    position -= (mParent == null ? 0 : 1);

    if (position < mDirs.length) {
      mDirectory = mDirs[position];
      mHandler.post(mUpdateFiles);
      return;
    }

    position -= mDirs.length;

    Uri uri = Uri.parse(mFiles[position].getAbsolutePath());
    Intent intent = new Intent(this, MuPDFActivity.class);
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(uri);
    startActivity(intent);
  }
        @Override
        public void run() {
          try {
            final Camera camera = cameraManager.open(surfaceHolder, !DISABLE_CONTINUOUS_AUTOFOCUS);

            final Rect framingRect = cameraManager.getFrame();
            final Rect framingRectInPreview = cameraManager.getFramePreview();

            runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    scannerView.setFraming(framingRect, framingRectInPreview);
                  }
                });

            final String focusMode = camera.getParameters().getFocusMode();
            final boolean nonContinuousAutoFocus =
                Camera.Parameters.FOCUS_MODE_AUTO.equals(focusMode)
                    || Camera.Parameters.FOCUS_MODE_MACRO.equals(focusMode);

            if (nonContinuousAutoFocus) cameraHandler.post(new AutoFocusRunnable(camera));

            cameraHandler.post(fetchAndDecodeRunnable);
          } catch (final IOException x) {
            log.info("problem opening camera", x);
            showDialog(DIALOG_CAMERA_PROBLEM);
          } catch (final RuntimeException x) {
            log.info("problem opening camera", x);
            showDialog(DIALOG_CAMERA_PROBLEM);
          }
        }
    @Override
    protected Object doInBackground(Object[] params) {
      ServerConnector connector = new ServerConnector(context);
      try {
        connector.synchronizeWithServer();
        handler.post(
            new Runnable() {
              public void run() {
                Toast.makeText(context, R.string.synchronize_success, Toast.LENGTH_SHORT).show();
              }
            });
      } catch (IOException | JSONException e) {
        handler.post(
            new Runnable() {
              public void run() {
                Toast.makeText(context, R.string.server_exception_text, Toast.LENGTH_SHORT).show();
              }
            });

      } catch (UnauthorizedException e) {
        handler.post(
            new Runnable() {
              public void run() {
                Toast.makeText(context, R.string.unauthorized_exception_text, Toast.LENGTH_SHORT)
                    .show();
              }
            });
        startSynchronizeActivity();
      }
      return null;
    }
 public void run() {
   if (!postToOnline()) {
     mHandler.post(mSentIncidentFail);
   } else {
     mHandler.post(mSentIncidentSuccess);
   }
 }
  public void showWhileExecuting(Runnable runnable) {
    showCalledCount++;
    if (showCalledCount > 1) {
      return;
    }
    show();
    HandlerThread backgroundThread = new HandlerThread("showWhileExecuting");
    backgroundThread.start();
    showWhileExecutingLooper = backgroundThread.getLooper();
    Handler handler = new Handler(showWhileExecutingLooper);
    handler.post(runnable);
    handler.post(
        new Runnable() {

          @Override
          public void run() {
            if (null != dialog && dialog.isShowing()) {
              mainHandler.post(
                  new Runnable() {

                    @Override
                    public void run() {
                      stopAnimation();
                      dialog.cancel();
                    }
                  });
            }
          }
        });
  }
 public void downloadfile(File file) {
   boolean uploadResult;
   File getfile =
       new File(
           Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
           file.getName());
   ;
   Log.e("FTP", "파일정보 : " + getfile.getPath() + "경로 : " + getfile.getAbsolutePath());
   try {
     outputstream = new FileOutputStream(getfile);
   } catch (FileNotFoundException e1) {
     // TODO Auto-generated catch block
     Log.e("FTP_SEND_ERR", "outputstream 생성 실패" + e1.toString());
     e1.printStackTrace();
   }
   try {
     FTPConnector.ftp.setFileType(FTP.BINARY_FILE_TYPE);
     uploadResult = FTPConnector.ftp.retrieveFile(file.getName(), outputstream);
     if (!uploadResult) {
       Log.e("FTP_SEND_ERR", "파일 전송을 실패하였습니다.");
       uploadResult = false;
       handler.post(failmsg);
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     Log.e("FTP_SEND_ERR", "파일 전송에 문제가 생겼습니다." + e.toString());
     uploadResult = false;
     handler.post(failmsg);
   }
 }
Exemple #8
0
 void applyFullscreen(boolean alreadyStarted) {
   boolean hasActionBar = ActionBarCompat.earlyHasActionBar();
   cachedFullscreen = prefs.getBoolean(FULLSCREEN_KEY, false);
   if (cachedFullscreen) {
     if (hasActionBar) {
       handler.post(
           new Runnable() {
             public void run() {
               actionBarCompat.lightsOut(getWindow(), gameView, true);
             }
           });
     } else if (alreadyStarted) {
       // This is the only way to change the theme
       if (!startedFullscreen) restartOnResume = true;
     } else {
       setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
     }
   } else {
     if (hasActionBar) {
       final boolean fAlreadyStarted = alreadyStarted;
       handler.post(
           new Runnable() {
             public void run() {
               actionBarCompat.lightsOut(getWindow(), gameView, false);
               // This shouldn't be necessary but is on Galaxy Tab 10.1
               if (fAlreadyStarted && startedFullscreen) restartOnResume = true;
             }
           });
     } else if (alreadyStarted && startedFullscreen) {
       // This is the only way to change the theme
       restartOnResume = true;
     } // else leave it as default non-fullscreen
   }
 }
  private void longClickAndDrag(
      final float xFrom, final float yFrom, final float xTo, final float yTo, final int steps) {
    Handler handler = new Handler(getActivity().getMainLooper());

    handler.post(
        new Runnable() {

          public void run() {
            MotionEvent downEvent =
                MotionEvent.obtain(
                    SystemClock.uptimeMillis(),
                    SystemClock.uptimeMillis(),
                    MotionEvent.ACTION_DOWN,
                    xFrom,
                    yFrom,
                    0);
            getActivity().dispatchTouchEvent(downEvent);
          }
        });

    solo.sleep(ViewConfiguration.getLongPressTimeout() + 200);

    handler.post(
        new Runnable() {
          public void run() {

            for (int i = 0; i <= steps; i++) {
              float x = xFrom + (((xTo - xFrom) / steps) * i);
              float y = yFrom + (((yTo - yFrom) / steps) * i);
              MotionEvent moveEvent =
                  MotionEvent.obtain(
                      SystemClock.uptimeMillis(),
                      SystemClock.uptimeMillis(),
                      MotionEvent.ACTION_MOVE,
                      x,
                      y,
                      0);
              getActivity().dispatchTouchEvent(moveEvent);
              solo.sleep(20);
            }
          }
        });

    solo.sleep(steps * 20 + 200);
    handler.post(
        new Runnable() {
          public void run() {
            MotionEvent upEvent =
                MotionEvent.obtain(
                    SystemClock.uptimeMillis(),
                    SystemClock.uptimeMillis(),
                    MotionEvent.ACTION_UP,
                    xTo,
                    yTo,
                    0);
            getActivity().dispatchTouchEvent(upEvent);
          }
        });
    solo.sleep(1000);
  }
    @Override
    public void run() {
      try {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
        String searchLanguageKey = getContext().getString(R.string.search_language_key);
        String searchLanguage =
            sp.getString(searchLanguageKey, getString(R.string.default_language_value));
        SearchEngine.Result result = engine.search(query, page, searchLanguage);

        Log.i(TAG, "language code passed:\"" + searchLanguage + "\"");
        if (runs) {
          h.post(new ResultRunnable(result, requestId));
        }
      } catch (Exception e) {
        e.printStackTrace();

        h.post(
            new Runnable() {
              @Override
              public void run() {
                setListShown(true);
                Toast.makeText(getActivity(), getString(R.string.network_error), Toast.LENGTH_SHORT)
                    .show();
              }
            });
      }
    }
Exemple #11
0
 @Override
 public void afterEvent(int event, int result, final Object data) {
   if (result == SMSSDK.RESULT_COMPLETE) {
     log("回调完成");
     if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
       log("提交验证码成功");
       handler.post(
           new Runnable() {
             @Override
             public void run() {
               if (mCallback != null) mCallback.success();
               mCallback = null;
             }
           });
     } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
       log("获取验证码成功");
     } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
       log("返回支持发送验证码的国家列表");
     }
   } else {
     log("Error:" + data.toString());
     handler.post(
         new Runnable() {
           @Override
           public void run() {
             if (mCallback != null) mCallback.error((Throwable) data);
             mCallback = null;
           }
         });
   }
 }
  private void switchUsbMassStorage(final boolean on) {
    // things to do on the UI thread
    mUIHandler.post(
        new Runnable() {
          @Override
          public void run() {
            switchDisplayBusy();
            // will be hidden once USB mass storage kicks in (or fails)
          }
        });

    // ActionsCode(author:songzhining, fix BUG00233310, gc for notifications)
    mGcCount = 0;
    mAsyncStorageHandler.post(mGcRunnable);

    // things to do elsewhere
    mAsyncStorageHandler.post(
        new Runnable() {
          @Override
          public void run() {
            if (on) {
              mStorageManager.enableUsbMassStorage();
            } else {
              mStorageManager.disableUsbMassStorage();
            }
          }
        });
  }
 public void run() {
   if (addToDb() == -1) {
     mHandler.post(mSentIncidentFail);
   } else {
     mHandler.post(mSentIncidentOfflineSuccess);
     // clearFields();
   }
 }
Exemple #14
0
  /*
   * Handle starting and ending connection
   */
  @Override
  public boolean onMenuItemSelected(int featureId, MenuItem item) {
    if (featureId == WindowUtils.FEATURE_VOICE_COMMANDS
        || featureId == Window.FEATURE_OPTIONS_PANEL) {
      switch (item.getItemId()) {
        case R.id.start_casting_menu_item:
          BaseCastingNetworkActivity.startCasting(PACKAGE_NAME, rootView);
          isCasting = true;
          break;

        case R.id.stop_casting_menu_item:
          BaseCastingNetworkActivity.stopCasting();
          isCasting = false;
          break;

        case R.id.see_quotes_menu_item:
          switch (mCardScrollView.getSelectedItemPosition()) {
            case 0: // Friedrich Nietzsche
              Log.d(PACKAGE_NAME, "Immersion to Friedrich Nietzsche quotes");

              mHandler.post(
                  new Runnable() {
                    @Override
                    public void run() {
                      Intent intent =
                          new Intent(MainActivity.this, QuotesFriedrichNietzscheActivity.class);
                      intent.putExtra(CASTING, isCasting);
                      startActivityForResult(intent, SHOW_QUOTES);
                    }
                  });

              break;

            case 1: // Lao Zi
              Log.d(PACKAGE_NAME, "Immersion to Lao Zi quotes");

              mHandler.post(
                  new Runnable() {
                    @Override
                    public void run() {
                      Intent intent = new Intent(MainActivity.this, QuotesLaoZiActivity.class);
                      intent.putExtra(CASTING, isCasting);
                      startActivityForResult(intent, SHOW_QUOTES);
                    }
                  });

              break;
          }
          break;

        default:
          return true;
      }
      return true;
    }
    // Good practice to pass through to super if not handled
    return super.onMenuItemSelected(featureId, item);
  }
  @Override
  public void searchEnd() {
    System.out.println("camera home activity search end call back");
    ArrayList<Device> deviceList = onvifMgr.getOnvifData().getDeviceList();
    handler.post(
        new Runnable() {
          @Override
          public void run() {
            progressBar.setVisibility(View.INVISIBLE);
          }
        });

    if (deviceList.size() <= 0) {
      handler.post(
          new Runnable() {
            @Override
            public void run() {
              Toast toast =
                  Toast.makeText(
                      getApplicationContext(), "没有搜索到设备,请确认摄像头在局域网内", Toast.LENGTH_SHORT);
              toast.setGravity(Gravity.CENTER, 0, 0);
              toast.show();
            }
          });

      return;
    }

    if (searchDeviceFlag == 1) {
      /*点击button*/
      searchDeviceFlag = 0;
      onResumeFlag = 1;
      Intent intent = new Intent();
      intent.setClass(CamerasGridActivity.this, DeviceListActivity.class);
      CamerasGridActivity.this.startActivity(intent);
    } else {
      int appUsingCount = onvifMgr.getAppUsingCount();
      System.out.println("appUsingCount ===" + appUsingCount);
      if (appUsingCount == 0) {
        onvifMgr.addAppUsingCount();
        onResumeFlag = 1;
        Intent intent = new Intent();
        intent.setClass(CamerasGridActivity.this, DeviceListActivity.class);
        CamerasGridActivity.this.startActivity(intent);
      } else {
        onvifMgr.addAppUsingCount();
        handler.post(
            new Runnable() {
              @Override
              public void run() {
                autoMatchAfterDiscoverEnd();
              }
            });
      }
    }
  }
 private void getTargets(final Target baseTarget) {
   if (null != baseTarget) {
     notifyOutboxHandlers(MESSAGE_START_LOADING, 0, 0, null);
     workerHandler.post(
         new Runnable() {
           @Override
           public void run() {
             // Load children of baseTarget
             ArrayList<Target> targets;
             try {
               targets = GraphiteConnection.getTargets(serverUrl, baseTarget.getName() + ".*", 1);
             } catch (Exception e) {
               e.printStackTrace();
               notifyOutboxHandlers(MESSAGE_STOP_LOADING, 0, 0, null);
               notifyOutboxHandlers(MESSAGE_FAIL_STAY, 0, 0, e);
               return;
             }
             synchronized (model) {
               int idx = model.indexOf(baseTarget);
               model.get(idx).setLoaded(true);
               idx++;
               for (int i = 0; i < targets.size(); ++i) {
                 model.add(idx + i, targets.get(i));
               }
               persistModel();
             }
             notifyOutboxHandlers(MESSAGE_MODEL_UPDATED, targets.size(), 0, baseTarget);
             notifyOutboxHandlers(MESSAGE_STOP_LOADING, 0, 0, null);
           }
         });
     return;
   }
   workerHandler.post(
       new Runnable() {
         @Override
         public void run() {
           TargetDao dao = new TargetDao();
           ArrayList<Target> targets = dao.getAll();
           String hash = String.valueOf((serverUrl + targetFilter).hashCode());
           if (0 < targets.size() && targets.get(0).getHash().equals(hash)) {
             synchronized (model) {
               while (model.size() > 0) {
                 model.remove(0);
               }
               for (Target target : targets) {
                 model.add(target);
               }
             }
             notifyOutboxHandlers(MESSAGE_MODEL_NEW, 0, 0, null);
           } else {
             // Force reload
             reloadTargets();
           }
         }
       });
 }
  @Override
  public boolean onInfo(MediaPlayer mp, int what, int extra) {
    Log.d(TAG, "onInfo what:" + what + ", extra:" + extra);

    switch (what) {
      case MediaPlayer.MEDIA_INFO_UNKNOWN:
        Log.d(TAG, "onInfo - MEDIA_INFO_UNKNOWN");
        break;

      case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
        Log.d(TAG, "onInfo - MEDIA_INFO_VIDEO_TRACK_LAGGING");
        break;

      case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
        Log.d(TAG, "onInfo - MEDIA_INFO_VIDEO_RENDERING_START");
        break;

      case MediaPlayer.MEDIA_INFO_BUFFERING_START:
        Log.d(TAG, "onInfo - MEDIA_INFO_BUFFERING_START");
        mHandler.post(
            new Runnable() {

              @Override
              public void run() {
                showProgress();
              }
            });
        break;

      case MediaPlayer.MEDIA_INFO_BUFFERING_END:
        Log.d(TAG, "onInfo - MEDIA_INFO_BUFFERING_END");
        mHandler.post(
            new Runnable() {

              @Override
              public void run() {
                hideProgress();
              }
            });
        break;

      case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
        Log.d(TAG, "onInfo - MEDIA_INFO_BAD_INTERLEAVING");
        break;

      case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
        Log.d(TAG, "onInfo - MEDIA_INFO_NOT_SEEKABLE");
        break;

      case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:
        Log.d(TAG, "onInfo - MEDIA_INFO_METADATA_UPDATE");
        break;
    }

    return false;
  }
 @Override
 public void drawThis(Object object) {
   if (object instanceof User) {
     User user = (User) object;
     handler.post(addMarker(user));
   } else if (object instanceof Task) {
     Task task = (Task) object;
     handler.post(showInRangeMessageBox());
   }
 }
Exemple #19
0
  private void prepareNextPage() {
    try {
      preparingWindow =
          forward ? slidingWindows.getNextWindow() : slidingWindows.getPreviousWindow();
      //// System.out.println("preparingWindow" + preparingWindow);
      if (preparingWindow.isLoading()) {
        // Log.d("SLIDING", "register on load listener...");

        handler.post(
            new Runnable() {
              public void run() {
                preparingWindow.registerOnLoadListener(
                    new com.goal98.flipdroid.model.Window.OnLoadListener() {

                      public void onWindowLoaded(com.goal98.flipdroid.model.Window window) {
                        if (forward) next = preparingWindow.get();
                        else {
                          previous = preparingWindow.get();
                        }
                        prepareFail = false;
                      }

                      public void onWindowSkipped(
                          com.goal98.flipdroid.model.Window pageViewWindow) {
                        prepareNextPage();
                      }
                    });
              }
            });
        return;
      } else if (preparingWindow.isSkip()) {
        // Log.d("SLIDING", "slide to next page...");
        prepareNextPage();
        return;
      } else {
        if (forward) next = preparingWindow.get();
        else previous = preparingWindow.get();

        handler.post(
            new Runnable() {
              public void run() {
                renderNextPageIfNotRendered();
                if (forward) next.removeLoadingIfNecessary();
                else previous.removeLoadingIfNecessary();
              }
            });
        prepareFail = false;
      }
    } catch (LastWindowException e) {
      prepareFail = true;
      e.printStackTrace();

      next = pageViewFactory.createLastPage();
    }
  }
Exemple #20
0
  public void processNormalProtocol(
      final Context context, ProgressDialog pd, final Runnable setModes) throws Exception {
    handler.post(drawableSetter);
    handler.post(setModes);
    handler.post(desktopInfo);

    // Hide progress dialog
    if (pd.isShowing()) pd.dismiss();

    rfb.processProtocol(this, connection.getUseLocalCursor());
  }
  @Override
  protected void onStart() {
    super.onStart();
    doBindService();

    _velHandler.removeCallbacks(_velCallback);
    _velHandler.post(_velCallback);

    _pidHandler.removeCallbacks(_pidCallback);
    _pidHandler.post(_pidCallback);
  }
Exemple #22
0
    @Override
    protected Void doInBackground(Uri... params) {

      if (params.length < 1) {
        Log.e(TAG, "ImageLoaderTask called with no Uri");
        return null;
      }

      try {
        Uri uri = params[0];

        // Decode the image from the Uri into a bitmap [1], and shrink it
        // according to the user's settings.
        // [1]:
        // http://stackoverflow.com/questions/13930009/how-can-i-get-an-image-from-another-application
        InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

        long maxAttachmentSize = SmsHelper.getSendSettings(mContext).getMaxAttachmentSize();
        bitmap = ImageUtils.shrink(bitmap, 90, maxAttachmentSize);

        // Now, rotation the bitmap according to the Exif data.
        final int rotation = ImageUtils.getOrientation(mContext, uri);
        Matrix matrix = new Matrix();
        matrix.postRotate(rotation);
        bitmap =
            Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        // Can't post UI updates on a background thread.
        final Bitmap imageBitmap = bitmap;
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                setAttachment(imageBitmap);
              }
            });

      } catch (FileNotFoundException | NullPointerException e) {
        // Make a toast to the user that the file they've requested to view
        // isn't available.
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                Toast.makeText(
                        mContext, mRes.getString(R.string.error_file_not_found), Toast.LENGTH_SHORT)
                    .show();
              }
            });
      }
      return null;
    }
  // 执行耗时操作,params[0]为url,params[1]为文件名(空则写入null)
  @Override
  protected Boolean doInBackground(String... params) {
    mTimer.schedule(mTask, 0, 500);
    try {
      mUrl = params[0];
      // 建立链接
      URLConnection connection = new URL(mUrl).openConnection();
      InputStream is = connection.getInputStream();
      // 先建立文件夹
      File fold = new File(getFolderPath());
      if (!fold.exists()) {
        fold.mkdirs();
      }
      String fileName = "";
      // 判断文件名:用户自定义或由url获得
      if (params[1] != null) {
        fileName = params[1];
      } else {
        fileName = getFileName(params[0]);
      }
      // 文件输出流
      FileOutputStream fos = new FileOutputStream(new File(getFolderPath() + fileName));

      byte[] buff = new byte[1024];
      int len;
      while ((len = is.read(buff)) != -1) {
        mTotalReadSize += len;
        fos.write(buff, 0, len);
      }
      fos.flush();
      fos.close();

    } catch (Exception e) {
      // 异常,下载失败
      mRunnable.setDatas(NOTIFICATION_PROGRESS_FAILED, 0L);
      // 发送显示下载失败
      mHandler.post(mRunnable);
      if (mTimer != null && mTask != null) {
        mTimer.cancel();
        mTask.cancel();
      }
      e.printStackTrace();
      return false;
    }
    // 下载成功
    mRunnable.setDatas(NOTIFICATION_PROGRESS_SUCCEED, 0L);
    mHandler.post(mRunnable);
    if (mTimer != null && mTask != null) {
      mTimer.cancel();
      mTask.cancel();
    }
    return true;
  }
  @Test
  public void testDefaultConstructorUsesDefaultLooper() throws Exception {
    Handler handler1 = new Handler();
    handler1.post(new Say("first thing"));

    Handler handler2 = new Handler(Looper.myLooper());
    handler2.post(new Say("second thing"));

    shadowOf(Looper.myLooper()).idle();

    transcript.assertEventsSoFar("first thing", "second thing");
  }
  @Override
  @NonNull
  public CacheDownloadLoader.Result loadInBackground() {
    if (mUri == null) {
      return Result.nullInstance();
    }
    final String scheme = mUri.getScheme();
    File cacheFile = null;
    if ("http".equals(scheme) || "https".equals(scheme)) {
      final String uriString = mUri.toString();
      if (uriString == null) return Result.nullInstance();
      cacheFile = mDiskCache.get(uriString);
      if (isValid(cacheFile)) {
        return Result.getInstance(CacheProvider.getCacheUri(uriString));
      }
      try {
        // from SD cache
        ContentLengthInputStream cis;
        final InputStream is = mDownloader.get(uriString);
        if (is == null) return Result.nullInstance();
        try {
          final long length = is.available();
          mHandler.post(new DownloadStartRunnable(this, mListener, length));

          cis = new ContentLengthInputStream(is, length);
          mDiskCache.save(
              uriString,
              cis,
              new IoUtils.CopyListener() {
                @Override
                public boolean onBytesCopied(int current, int total) {
                  mHandler.post(new ProgressUpdateRunnable(mListener, current, total));
                  return !isAbandoned();
                }
              });
          mHandler.post(new DownloadFinishRunnable(this, mListener));
        } finally {
          Utils.closeSilently(is);
        }
        cacheFile = mDiskCache.get(uriString);
        if (isValid(cacheFile)) {
          return Result.getInstance(CacheProvider.getCacheUri(uriString));
        } else {
          mDiskCache.remove(uriString);
          throw new IOException();
        }
      } catch (final Exception e) {
        mHandler.post(new DownloadErrorRunnable(this, mListener, e));
        return Result.getInstance(e);
      }
    }
    return Result.getInstance(mUri);
  }
 @Subscribe
 public void react(final OttoMessage message) {
   if (handler != null) {
     if (message.getMessageType().equals(OttoMessage.MessageType.ResultArticle)) {
       handler.post(
           new Runnable() {
             @Override
             public void run() {
               ArticlesAdapter adapter = (ArticlesAdapter) recList.getAdapter();
               articlesList = ((ResultArticle) message).getArticles();
               TextView no_Results = (TextView) getActivity().findViewById(R.id.NoResultMessage);
               if (articlesList.size() != 0) {
                 noResults = false;
                 no_Results.setVisibility(View.GONE);
               } else {
                 noResults = true;
                 no_Results.setVisibility(View.VISIBLE);
               }
               adapter.setArticles(articlesList);
               adapter.notifyDataSetChanged();
             }
           });
     } else if (message.getMessageType().equals(OttoMessage.MessageType.UpdateAdapter)) {
       handler.post(
           new Runnable() {
             @Override
             public void run() {
               ArticlesAdapter adapter = (ArticlesAdapter) recList.getAdapter();
               adapter.notifyDataSetChanged();
             }
           });
     } else if (message.getMessageType().equals(OttoMessage.MessageType.NoResult)) {
       handler.post(
           new Runnable() {
             @Override
             public void run() {
               Toast.makeText(getActivity(), "No article found", Toast.LENGTH_SHORT).show();
             }
           });
     } else if (message.getMessageType().equals(OttoMessage.MessageType.NoInternet)) {
       handler.post(
           new Runnable() {
             @Override
             public void run() {
               Toast.makeText(getActivity(), "No internet", Toast.LENGTH_SHORT).show();
             }
           });
     }
   }
 }
  @Test
  public void testInsertsRunnablesBasedOnLooper() throws Exception {
    Looper looper = newLooper(false);

    Handler handler1 = new Handler(looper);
    handler1.post(new Say("first thing"));

    Handler handler2 = new Handler(looper);
    handler2.post(new Say("second thing"));

    shadowOf(looper).idle();

    transcript.assertEventsSoFar("first thing", "second thing");
  }
 @Override
 public void onReceive(Context context, Intent intent) {
   final String action = intent.getAction();
   if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
       || Intent.ACTION_PACKAGE_REMOVED.equals(action)
       || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
     Log.i(TAG, "action: " + action);
     final String packageName = intent.getData().getSchemeSpecificPart();
     final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
     int op = PackageUpdatedTask.OP_NONE;
     if (packageName == null || packageName.length() == 0) {
       // they sent us a bad intent
       return;
     }
     if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
       op = PackageUpdatedTask.OP_UPDATE;
     } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
       if (!replacing) {
         op = PackageUpdatedTask.OP_REMOVE;
       }
     } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
       if (!replacing) {
         op = PackageUpdatedTask.OP_ADD;
       } else {
         op = PackageUpdatedTask.OP_UPDATE;
       }
     }
     mHandler.post(new PackageUpdatedTask(op, new String[] {packageName}));
   } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
     Log.i(TAG, "ACTION_EXTERNAL_APPLICATIONS_AVAILABLE");
     String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
     int op = PackageUpdatedTask.OP_ADD;
     mHandler.post(new PackageUpdatedTask(op, packages));
   } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
     Log.i(TAG, "ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE");
     String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
     int op = PackageUpdatedTask.OP_REMOVE;
     mHandler.post(new PackageUpdatedTask(op, packages));
   } else if (Intent.ACTION_TIME_TICK.equals(action)
       || Intent.ACTION_TIME_CHANGED.equals(action)
       || Intent.ACTION_TIMEZONE_CHANGED.equals(action)) {
     timeChanged();
   } else if (FavoritesModel.ACTION_FAVOTITE_UPDATE.equals(action)) {
     Log.i(TAG, "ACTION_FAVOTITE_UPDATE");
     FavoritesData.saveFavoritesToDatabase(mContext);
     FavoritesData.sort();
   }
 }
 public boolean execute(Runnable r) {
   if (handler != null) {
     Log.i("CommonWorkingThread", ">>> working thread execute ");
     return handler.post(r);
   }
   return false;
 }
Exemple #30
0
  public void run() {
    final Latitude latitude;
    final Longitude longitude;
    final WindshieldWiperStatus wiperStatus;
    try {
      latitude = (Latitude) mVehicle.get(Latitude.class);
      longitude = (Longitude) mVehicle.get(Longitude.class);
      wiperStatus = (WindshieldWiperStatus) mVehicle.get(WindshieldWiperStatus.class);
    } catch (UnrecognizedMeasurementTypeException e) {
      return;
    } catch (NoValueException e) {
      Log.w(TAG, "One or more of the required measurements" + " didn't have a value", e);
      return;
    }

    final boolean wiperStatusValue;
    wiperStatusValue = wiperStatus.getValue().booleanValue();

    mHandler.post(
        new Runnable() {
          public void run() {
            String wiperText;
            if (wiperStatusValue) {
              wiperText = "on";
            } else {
              wiperText = "off";
            }
            mWiperStatusView.setText(wiperText);
          }
        });
    uploadWiperStatus(latitude, longitude, wiperStatus);
  }