Java Code Examples for android.os.Handler

The following are top voted examples for showing how to use android.os.Handler. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Renrentou   File: AdCompanySearchActivity.java   View source code 8 votes vote down vote up
private void initPullToRefreshLayout(){
    pullToRefreshLayout.setRefreshListener(new BaseRefreshListener() {
        @Override
        public void refresh() {
            if(list.isEmpty()){
                pullToRefreshLayout.showView(ViewStatus.LOADING_STATUS);
            }
            getP().refresh(searchText);
        }

        @Override
        public void loadMore() {
            getP().loadMore(searchText);
        }
    });

    pullToRefreshLayout.showView(ViewStatus.LOADING_STATUS);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            getP().refresh();
        }
    }, 500);
}
 
Example 2
Project: react-native-webrtc   File: WebRTCModule.java   View source code 8 votes vote down vote up
public WebRTCModule(ReactApplicationContext reactContext) {
    super(reactContext);

    imageProcessingThread = new HandlerThread("PictureProcessing");
    imageProcessingThread.start();
    imagePorcessingHandler = new Handler(imageProcessingThread.getLooper());

    mPeerConnectionObservers = new SparseArray<PeerConnectionObserver>();
    mMediaStreams = new HashMap<String, MediaStream>();
    mMediaStreamTracks = new HashMap<String, MediaStreamTrack>();
    mVideoCapturers = new HashMap<String, VideoCapturer>();
    mCameras = new HashMap<>();

    pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
    pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"));
    pcConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));

    PeerConnectionFactory.initializeAndroidGlobals(reactContext, true, true, true);
    mFactory = new PeerConnectionFactory();
}
 
Example 3
Project: appinventor-extensions   File: Twitter.java   View source code 7 votes vote down vote up
public Twitter(ComponentContainer container) {
  super(container.$form());
  this.container = container;
  handler = new Handler();

  mentions = new ArrayList<String>();
  followers = new ArrayList<String>();
  timeline = new ArrayList<List<String>>();
  directMessages = new ArrayList<String>();
  searchResults = new ArrayList<String>();

  sharedPreferences = container.$context().getSharedPreferences("Twitter",
      Context.MODE_PRIVATE);
  accessToken = retrieveAccessToken();

  requestCode = form.registerForActivityResult(this);
}
 
Example 4
Project: notify-me   File: HeadPhoneListener.java   View source code 6 votes vote down vote up
private void initSpeechRecognizer() {
    Log.e(TAG, "initSpeechRecognizer: ");

    Handler handler = getHandler();

    mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(mContext);
    final Intent recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    recognizerIntent.putExtra(
            RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
            mContext.getPackageName());

    mSpeechRecognizer.setRecognitionListener(new SpeechListener(handler));
    mSpeechRecognizer.startListening(recognizerIntent);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mSpeechRecognizer.stopListening();
        }
    }, DELAY_MILLIS);
}
 
Example 5
Project: Trivia-Knowledge   File: MainGameActivity.java   View source code 6 votes vote down vote up
private void allAnimation() {

        //Animation
        final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.bounce);
        // Use bounce interpolator with amplitude 0.2 and frequency 20
        MyBounceInterpolator interpolator = new MyBounceInterpolator(0.11, 10);
        myAnim.setInterpolator(interpolator);
        tvQ.startAnimation(myAnim);


        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {

            public void run() {
                master.startAnimation(inFromLeftAnimation());
                master.setVisibility(View.VISIBLE);   //for interval...
            }
        };
        handler.postDelayed(runnable, 150); //for initial delay..*//*

        for (int i = 0; i < 20; i++) {
            textViewArrayAbove[i].startAnimation(myAnim);
        }
    }
 
Example 6
Project: NoticeDog   File: NotificationManager.java   View source code 6 votes vote down vote up
public void removeNotificationsForSMS(String smsPackage, String from, String address, String displayAddress, String body, long timestamp) {
    if (!this.keepNotificationsInDrawer) {
        final String str = smsPackage;
        final String str2 = from;
        final String str3 = address;
        final String str4 = displayAddress;
        final String str5 = body;
        final long j = timestamp;
        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                Intent i = new Intent(NotificationService.INTENT_ACTION_CMDS);
                i.putExtra("command", NotificationService.CMD_REMOVE_SMS);
                i.putExtra(NotificationService.KEY_SMS_PACKAGE, str);
                i.putExtra(NotificationService.KEY_SMS_FROM, str2);
                i.putExtra(NotificationService.KEY_SMS_ADDRESS, str3);
                i.putExtra(NotificationService.KEY_SMS_DISPLAY_ADDRESS, str4);
                i.putExtra(NotificationService.KEY_SMS_BODY, str5);
                i.putExtra(NotificationService.KEY_SMS_TIMESTAMP, j);
                NotificationManager.this.context.sendBroadcast(i);
            }
        };
        handler.sendMessageDelayed(handler.obtainMessage(), 3000);
    }
}
 
Example 7
Project: amap   File: HERBServiceImpl.java   View source code 6 votes vote down vote up
/**
 * 
 * 获取海尔人报列表
 * 
 * @Description<功能详细描述>
 * 
 * @param task
 * @param handler
 * @param requestType
 * @param maxId
 * @param pageSize
 * @return
 * @LastModifiedDate:2016年10月28日
 * @author wl
 * @EditHistory:<修改内容><修改人>
 */
public static NetTask getHaierNspList(NetTask task, Handler handler, int requestType, String maxId, String pageSize)
{
    
    JSONObject bodyVaule = new JSONObject();
    try
    {
        bodyVaule.put("maxId", maxId);
        bodyVaule.put("pageSize", pageSize);
    }
    catch (JSONException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JSONObject requestObj =
        NetRequestController.getPredefineObj("newspaper",
            "HaierNspAdapter",
            "getHaierNspList",
            "general",
            bodyVaule);
    
    return NetRequestController.sendStrBaseServlet(task, handler, requestType, requestObj);
}
 
Example 8
Project: chromium-for-android-56-debug-video   File: UpgradeActivity.java   View source code 6 votes vote down vote up
public UpgradeActivity() {
    mHandler = new Handler(Looper.getMainLooper());

    mObserver = new DocumentModeAssassinObserver() {
        @Override
        public void onStageChange(int newStage) {
            if (newStage != DocumentModeAssassin.STAGE_DONE) return;
            DocumentModeAssassin.getInstance().removeObserver(this);

            // Always post to avoid any issues that could arise from firing the Runnable
            // while other Observers are being alerted.
            long msElapsed = System.currentTimeMillis() - mStartTimestamp;
            long msRemaining = Math.max(0, MIN_MS_TO_DISPLAY_ACTIVITY - msElapsed);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    continueApplicationLaunch();
                }
            }, msRemaining);
        }
    };
}
 
Example 9
Project: LabDayApp   File: MainActivity.java   View source code 6 votes vote down vote up
/**
 * discard back press if MainFragment loaded, double tap to app exit
 */
@Override
public void onBackPressed() {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragmentLayout);
    if(fragment instanceof MainFragment || fragment instanceof LoginFragment){
        if(doubleBackToExit) {
            finish();
            return;
        }

        doubleBackToExit = true;
        Toast.makeText(this, getString(R.string.double_back_info), Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(() -> doubleBackToExit = false, 2000);

        return;
    }

    super.onBackPressed();
}
 
Example 10
Project: amap   File: JueYiSeviceImpl.java   View source code 6 votes vote down vote up
/**
 * 
 * 获取详情
 * 
 * @Description<功能详细描述>
 * 
 * @param task
 * @param handler
 * @param requestType
 * @param id 决议/汇报id
 * @return
 * @LastModifiedDate:2016年9月21日
 * @author wl
 * @EditHistory:<修改内容><修改人>
 */
public static NetTask sendGetResultDetailRequest(NetTask task, Handler handler, int requestType, String id)
{
    
    JSONObject bodyVaule = new JSONObject();
    try
    {
        bodyVaule.put("id", id);
    }
    catch (JSONException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JSONObject requestObj =
        NetRequestController.getPredefineObj("result", "ResultAdapter", "getResultDetail", "general", bodyVaule);
    
    return NetRequestController.sendStrBaseServlet(task, handler, requestType, requestObj);
}
 
Example 11
Project: Kids-Portal-Android   File: helper_editText.java   View source code 6 votes vote down vote up
public static void showKeyboard(final Activity activity, final EditText editText, final int i, String text, String hint) {
    editText.requestFocus();
    editText.hasFocus();
    editText.setText(text);
    editText.setHint(hint);
    editText.setSelection(editText.length());
    new Handler().postDelayed(new Runnable() {
        public void run() {
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity);
            sharedPref.edit().putInt("keyboard", i).apply();
            activity.invalidateOptionsMenu();
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        }
    }, 200);
}
 
Example 12
Project: mupdf-android-viewer-old   File: MuPDFReflowView.java   View source code 6 votes vote down vote up
public MuPDFReflowView(Context c, MuPDFCore core, Point parentSize) {
	super(c);
	mHandler = new Handler();
	mCore = core;
	mParentSize = parentSize;
	mScale = 1.0f;
	mContentHeight = parentSize.y;
	getSettings().setJavaScriptEnabled(true);
	addJavascriptInterface(new Object(){
		public void reportContentHeight(String value) {
			mContentHeight = (int)Float.parseFloat(value);
			mHandler.post(new Runnable() {
				public void run() {
					requestLayout();
				}
			});
		}
	}, "HTMLOUT");
	setWebViewClient(new WebViewClient() {
		@Override
		public void onPageFinished(WebView view, String url) {
			setScale(mScale);
		}
	});
}
 
Example 13
Project: mvvm-template   File: ProfileActivity.java   View source code 6 votes vote down vote up
public void onUserUpdated(@Nullable UserDetail user) {
    if (user != null) {

        if (binding.viewPager.getAdapter() == null) {
            new Handler(Looper.myLooper()).postDelayed(this::initPager, 300);
        }

        binding.tvName.setText(user.getDisplayName());
        binding.tvLink.setText(user.getHtmlUrl());

        if (InputHelper.isEmpty(user.getBio())) {
            binding.tvBio.setVisibility(View.GONE);
        } else {
            binding.tvBio.setVisibility(View.VISIBLE);
            binding.tvBio.setText(user.getBio());
        }
        GlideUtils.loadImageBitmap(this, user.getAvatarUrl(), bitmap -> {
            binding.imvAvatar.setImageBitmap(bitmap);
            Blurry.with(this).radius(25).from(bitmap).into(binding.imvBackground);
        });
    }
}
 
Example 14
Project: Personal-Chef   File: Splash.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    background = (ImageView) findViewById(R.id.s_img);



    Glide.with(this)
            .load(R.drawable.splash)
            .into(background);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 100ms
            finish();
            startActivity(new Intent(Splash.this, Home.class));
        }
    }, 3000);
}
 
Example 15
Project: AndEasyLog   File: ThreadHelper.java   View source code 6 votes vote down vote up
private ThreadHelper() {
    mMainHandler = new Handler(Looper.getMainLooper());
    ThreadFactory threadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "ThreadHelper #".concat(String.valueOf(mCount.getAndIncrement())));
        }
    };
    int cpuCount = Runtime.getRuntime().availableProcessors();
    int corePoolSize = cpuCount + 1;
    int maxPoolSize = cpuCount * 2 + 1;
    BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(128);
    mExecutorService = new ThreadPoolExecutor(corePoolSize, maxPoolSize, 10, TimeUnit.SECONDS, queue, threadFactory);
}
 
Example 16
Project: Carousel   File: CarouselView.java   View source code 6 votes vote down vote up
public CarouselView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.context = context;
    initTypedArray(attrs);
    bindView(context);
    initView();
    handler = new Handler(this);
    carouselLifecycleListener = new CarouselLifecycleListener() {
        @Override
        public void onStop() {
            if (isAutoSwitch) {
                stop();
            }
        }

        @Override
        public void onResume() {
            if (isAutoSwitch) {
                resume();
            }
        }
    };
}
 
Example 17
Project: StatusView   File: PageFragment.java   View source code 6 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
	super.onActivityCreated(savedInstanceState);
	switch (mPageIndex) {
		case 0:
			mCenterText.setText("HOME");
			break;
		case 1:
			mCenterText.setText("MESSAGE");
			break;
		case 2:
			mCenterText.setText("MINE");
			break;
	}

	mStatusView.setStatus(Status.LOADING);
	new Handler().postDelayed(new Runnable() {
		@Override
		public void run() {
			mStatusView.setStatus(Status.NORMAL);
		}
	}, 2000);
}
 
Example 18
Project: fast_face_android   File: OnGetImageListener.java   View source code 6 votes vote down vote up
public void initialize(
        final Context context,
        final AssetManager assetManager,
        final TrasparentTitleView scoreView,
        final Handler handler) {
    this.mContext = context;
    this.mTransparentTitleView = scoreView;
    this.mInferenceHandler = handler;
    mFaceDet = new FaceDet(Constants.getFaceShapeModelPath());
    mWindow = new FloatingCameraWindow(mContext);

    mFaceLandmardkPaint = new Paint();
    mFaceLandmardkPaint.setColor(Color.GREEN);
    mFaceLandmardkPaint.setStrokeWidth(2);
    mFaceLandmardkPaint.setStyle(Paint.Style.STROKE);
}
 
Example 19
Project: Blockly   File: CodeGeneratorService.java   View source code 6 votes vote down vote up
@Override
public void onCreate() {
    mHandler = new Handler();
    mWebview = new WebView(this);
    mWebview.getSettings().setJavaScriptEnabled(true);
    mWebview.setWebChromeClient(new WebChromeClient());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
    mWebview.addJavascriptInterface(new BlocklyJavascriptInterface(),
            "BlocklyJavascriptInterface");

    mWebview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            synchronized (this) {
                mReady = true;
            }
            handleRequest();
        }
    });
    mWebview.loadUrl(BLOCKLY_COMPILER_PAGE);
}
 
Example 20
Project: LucaHome-AndroidApplication   File: ScheduleEditActivity.java   View source code 6 votes vote down vote up
private void navigateBack(@NonNull String message) {
    Snacky.builder()
            .setActivty(ScheduleEditActivity.this)
            .setText(message)
            .setDuration(Snacky.LENGTH_INDEFINITE)
            .success()
            .show();

    new Handler().postDelayed(() -> {
        NavigationService.NavigationResult navigationResult = NavigationService.getInstance().GoBack(ScheduleEditActivity.this);
        if (navigationResult != NavigationService.NavigationResult.SUCCESS) {
            Logger.getInstance().Error(TAG, String.format(Locale.getDefault(), "Navigation failed! navigationResult is %s!", navigationResult));
            displayErrorSnackBar("Failed to navigate back! Please contact LucaHome support!");
        }
    }, 1500);
}
 
Example 21
Project: threatasserter   File: KotlinTestTest.java   View source code 6 votes vote down vote up
@Test(timeout = 2000)
public void crashIfRunningOnUiThread() throws InterruptedException {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    new Handler(Looper.getMainLooper())
            .post(new Runnable() {
                @Override
                public void run() {
                    try {
                        new KotlinTest().crashIfNotWorkerThread();
                    } catch (Exception e) {
                        throwable.set(e);
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
    countDownLatch.await();

    assertNotNull(throwable.get());
    assertSame(throwable.get().getClass(), IllegalStateException.class);
    assertEquals("This method must be run on a worker thread.", throwable.get().getMessage());
}
 
Example 22
Project: amap   File: YDKQServiceImpl.java   View source code 6 votes vote down vote up
/**
 * 获取当天考勤记录 <一句话功能简述>
 * 
 * @Description<功能详细描述>
 * 
 * @param task
 * @param handler
 * @param requestType
 * @param todayDate
 * @return
 * @LastModifiedDate:2017-5-8
 * @author zxm
 * @EditHistory:<修改内容><修改人>
 */
public static NetTask getClockList(NetTask task, Handler handler, int requestType, String todayDate)
{
    JSONObject bodyVaule = new JSONObject();
    try
    {
        bodyVaule.put("date", todayDate);
    }
    catch (JSONException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JSONObject requestObj =
        NetRequestController.getPredefineObj("attendance",
            "AttendanceAdapter",
            "getClockList",
            "general",
            bodyVaule);
    
    return NetRequestController.getClockList(task, handler, requestType, requestObj);
}
 
Example 23
Project: letv   File: ImageActivity.java   View source code 6 votes vote down vote up
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    requestWindowFeature(1);
    setRequestedOrientation(1);
    setContentView(a());
    this.d = new Handler();
    Bundle bundleExtra = getIntent().getBundleExtra(Constants.KEY_PARAMS);
    this.r = bundleExtra.getString(SocialConstants.PARAM_AVATAR_URI);
    this.c = bundleExtra.getString("return_activity");
    String string = bundleExtra.getString("appid");
    String string2 = bundleExtra.getString("access_token");
    long j = bundleExtra.getLong("expires_in");
    String string3 = bundleExtra.getString("openid");
    this.n = bundleExtra.getInt("exitAnim");
    this.b = new QQToken(string);
    this.b.setAccessToken(string2, ((j - System.currentTimeMillis()) / 1000) + "");
    this.b.setOpenId(string3);
    b();
    e();
    this.m = System.currentTimeMillis();
    a("10653", 0);
}
 
Example 24
Project: Android-Firewall   File: Util.java   View source code 5 votes vote down vote up
public static void toast(final String text, final int length, final Context context) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(context, text, length).show();
        }
    });
}
 
Example 25
Project: NanoIconPack   File: WhatsNewActivity.java   View source code 5 votes vote down vote up
@Override
public void onLoadDone(int pageId, int sum) {
    (new Handler()).postDelayed(new Runnable() {
        @Override
        public void run() {
            showHint();
        }
    }, 400);
}
 
Example 26
Project: browser   File: BrowserActivity.java   View source code 5 votes vote down vote up
void refreshWebPage(){
	new Handler().postDelayed(new Runnable() {
		@Override
		public void run() {
			runRefreshWebPage();
			// mDemoSlider.removeAllSliders();
		}
	}, 200);
}
 
Example 27
Project: xwallet   File: RecoverFragment.java   View source code 5 votes vote down vote up
/**
 *
 * @param seed
 */
public void promptWalletRecovery(final String seed) {
    new SweetAlertDialog(getBaseActivity(), SweetAlertDialog.NORMAL_TYPE)
            .setTitleText("Recovery")
            .setContentText("You sure you want to recover wallet from the seed : " + seed + " ? \n\n This might take some time, please keep your phone plugged in!")
            .setConfirmText("Yes, Recover!")
            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    getBaseActivity().recoverWallet(CoinManagerFactory.BITCOIN, seed, _lastDateSet);
                    Toast.makeText(RecoverFragment.this.getBaseActivity(), "Initiating recovery... Please wait!", Toast.LENGTH_SHORT).show();

                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            getBaseActivity().showMenuSelection(0);
                        }
                    }, 500);

                    sDialog.dismissWithAnimation();
                }
            })
            .setCancelText("Cancel")
            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.cancel();
                }
            })
            .show();
}
 
Example 28
Project: Amazing   File: SendFlowersActivity.java   View source code 5 votes vote down vote up
private void startA() {
    flowerGiftView.startAnim(5);
    Handler handler = new Handler(getMainLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {

        }
    });
}
 
Example 29
Project: react-native-apptentive-module   File: RNApptentiveModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void presentMessageCenterWithCustomData(ReadableMap customData, final Promise promise)
{
	if (customData == null)
	{
		this.presentMessageCenter(promise);
		return;
	}
	if (!_initialised)
	{
		promise.reject(APPTENTIVE, "Apptentive is not initialised");
		return;
	}
	if (!Apptentive.canShowMessageCenter())
	{
		promise.reject(APPTENTIVE, "Apptentive message center can't be shown");
		return;
	}
	if (!(customData instanceof ReadableNativeMap))
	{
		promise.reject(APPTENTIVE, "Apptentive can't handle this customData");
		return;
	}

	ReadableNativeMap nativeMap = (ReadableNativeMap) customData;
	final HashMap<String, Object> hashMap = nativeMap.toHashMap();

	Handler handler = new Handler(_application.getMainLooper());
	Runnable runnable = new Runnable()
	{
		@Override
		public void run()
		{
			boolean shown = Apptentive.showMessageCenter(getReactApplicationContext(), hashMap);
			promise.resolve(shown);
		}
	};
	handler.post(runnable);
}
 
Example 30
Project: Presenter-Client-Android   File: BluetoothPresenterControlTest.java   View source code 5 votes vote down vote up
/**
 * Test that the "error" event is sent successfully if the server sends invalid data.
 */
@Test
public void testConnectedEventInvalidData() throws InterruptedException {
    ShadowBluetoothSocket.setTransmittedString("This is invalid json data\n\n");
    final CountDownLatch messageReceived = new CountDownLatch(1);

    control = new BluetoothPresenterControl(new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == RemoteControl.ServiceState.ERROR.ordinal()) {
                assertThat("Got wrong error type",
                        msg.getData().getString(RemoteControl.RESULT_VALUES[2]),
                        is(RemoteControl.ERROR_TYPES.PARSING.toString()));

                messageReceived.countDown();
            }
        }
    });
    BluetoothDevice bluetoothDevice = ShadowBluetoothAdapter.getDefaultAdapter()
            .getRemoteDevice(DEVICE_ADDRESS);
    control.connect(bluetoothDevice);
    waitForServiceStateChanged(control, RemoteControl.ServiceState.CONNECTING);

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < startTime + MESSAGE_RECEIVING_TIMEOUT) {
        Thread.sleep(MESSAGE_CHECK_TIME);
        ShadowLooper.runUiThreadTasks();
        if (messageReceived.await(MESSAGE_CHECK_TIME, TimeUnit.MILLISECONDS)) {
            return;
        }
    }
    fail("Did not receive 'error' event");
}
 
Example 31
Project: ucar-weex-core   File: UWXFrameBaseActivity.java   View source code 5 votes vote down vote up
private void setTranslateAnimation(View view) {
    UWLog.v("FrameBaseActivity>start Animation():" + System.currentTimeMillis());
    if (view != null) {
        TranslateAnimation translateAnimation = new TranslateAnimation((float) this.getResources().getDisplayMetrics().widthPixels, 0.0F, 0.0F, 0.0F);
        translateAnimation.setDuration(200L);
        view.startAnimation(translateAnimation);
        view.setVisibility(View.VISIBLE);
        this.mContainer.setBackgroundColor(-1);
        (new Handler()).postDelayed(new Runnable() {
            public void run() {
                UWXFrameBaseActivity.this.mContainer.setBackgroundColor(-1);
            }
        }, 220L);
    }
}
 
Example 32
Project: CCDownload   File: MediaPlayActivity.java   View source code 5 votes vote down vote up
private void initPlayHander() {
	playerHandler = new Handler() {
		public void handleMessage(Message msg) {

			if (player == null) {
				return;
			}

			// 刷新字幕
			subtitleText.setText(subtitle.getSubtitleByTime(player
					.getCurrentPosition()));

			// 更新播放进度
			currentPlayPosition = player.getCurrentPosition();
			int duration = player.getDuration();

			if (duration > 0) {
				long pos = skbProgress.getMax() * currentPlayPosition / duration;
				playDuration.setText(ParamsUtil.millsecondsToStr(player.getCurrentPosition()));
				skbProgress.setProgress((int) pos);
			}
		};
	};

	

}
 
Example 33
Project: sdl_video_streaming_android_sample   File: SdlService.java   View source code 5 votes vote down vote up
public void notifyStreaming(){
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(getApplicationContext(),
                    "Streaming to module",
                    Toast.LENGTH_SHORT).show();
        }
    });
}
 
Example 34
Project: EasyIPC   File: MainService.java   View source code 5 votes vote down vote up
@Override public void onCreate() {
	super.onCreate();

	dispatchEvent(new EarlyData("sent from the service")); // get's queued

	handler = new Handler();
	handler.postDelayed(dispatchSingleData, 1333);
	handler.postDelayed(dispatchListData, 2500);

	addListener(Data.class, this);
	addListener(EarlyData.class, onEarlyData);
}
 
Example 35
Project: KUtils-master   File: Countdown.java   View source code 5 votes vote down vote up
/**
 * 创建一个倒计时器
 * @param textViewGetListener 显示倒计时的文本视图获取监听器
 * @param countdownText 倒计时中显示的内容,例如:"%s秒后重新获取验证码",在倒计时的过程中会用剩余描述替换%s
 * @param remainingSeconds 倒计时秒数,例如:60,就是从60开始倒计时一直到0结束
 */
public Countdown(TextViewGetListener textViewGetListener, String countdownText, int remainingSeconds){
    this.textViewGetListener = textViewGetListener;
    this.countdownText = countdownText;
    this.remainingSeconds = remainingSeconds;
    this.handler = new Handler();
}
 
Example 36
Project: Pocket-Plays-for-Twitch   File: IabHelper.java   View source code 5 votes vote down vote up
void consumeAsyncInternal(final List<Purchase> purchases,
                          final OnConsumeFinishedListener singleListener,
                          final OnConsumeMultiFinishedListener multiListener)
    throws IabAsyncInProgressException {
    final Handler handler = new Handler();
    flagStartAsync("consume");
    (new Thread(new Runnable() {
        public void run() {
            final List<IabResult> results = new ArrayList<IabResult>();
            for (Purchase purchase : purchases) {
                try {
                    consume(purchase);
                    results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku()));
                }
                catch (IabException ex) {
                    results.add(ex.getResult());
                }
            }

            flagEndAsync();
            if (!mDisposed && singleListener != null) {
                handler.post(new Runnable() {
                    public void run() {
                        singleListener.onConsumeFinished(purchases.get(0), results.get(0));
                    }
                });
            }
            if (!mDisposed && multiListener != null) {
                handler.post(new Runnable() {
                    public void run() {
                        multiListener.onConsumeMultiFinished(purchases, results);
                    }
                });
            }
        }
    })).start();
}
 
Example 37
Project: letv   File: AsynLoadImg.java   View source code 5 votes vote down vote up
public AsynLoadImg(Activity activity) {
    this.e = new Handler(this, activity.getMainLooper()) {
        final /* synthetic */ AsynLoadImg a;

        public void handleMessage(Message message) {
            f.a("AsynLoadImg", "handleMessage:" + message.arg1);
            if (message.arg1 == 0) {
                this.a.b.saved(message.arg1, (String) message.obj);
            } else {
                this.a.b.saved(message.arg1, null);
            }
        }
    };
}
 
Example 38
Project: VirtualAPK   File: RunUtil.java   View source code 5 votes vote down vote up
private static Handler getHandler() {
    synchronized (RunUtil.class) {
        if (sHandler == null) {
            sHandler = new InternalHandler();
        }
        return sHandler;
    }
}
 
Example 39
Project: Hotspot-master-devp   File: MediaUtils.java   View source code 5 votes vote down vote up
public static void getFolderAllImg(Context context, List<PictureInfo> datas, List<String> childList,final Handler handler) {
        for (int i = 0; i < childList.size(); i++) {
            int startTitle = childList.get(i).lastIndexOf("/") + 1;
            int endTitle = childList.get(i).lastIndexOf(".");
            String title = (String) childList.get(i).subSequence(startTitle, endTitle);
            String filename = childList.get(i);

            PictureInfo model = new PictureInfo();
            model.setFunction(ConstantsWhat.FunctionsIds.PREPARE);
            model.setAction("2screen");
            model.setAssettype("pic");
            model.setAssetname(title);
            model.setAssetpath(filename);
//            if (contains(context, title)) {
//                if (application == null) {
//                    application = (SavorApplication) context.getApplicationContext();
//                }
//                model.setAsseturl(application.GalleyPath + title + ".jpg");
//            } else {
            model.setAsseturl(NetWorkUtil.getLocalUrl(context) + filename);
//            }
            datas.add(model);
        }

        handler.sendEmptyMessage(INIT_SUCCESS);
        // calback.setData();
    }
 
Example 40
Project: quickblox-android   File: CallActivity.java   View source code 5 votes vote down vote up
private void setAudioDeviceDelayed(final AppRTCAudioManager.AudioDevice audioDevice) {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            showToastAfterHeadsetPlugged = true;
            audioManager.setAudioDevice(audioDevice);
        }
    }, 500);
}