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   Source Code and License 10 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   Source Code and License 9 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   Source Code and License 8 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 7 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: GitHub   File: DiskLogStrategyTest.java   Source Code and License 5 votes vote down vote up
@Test public void log() {
  Handler handler = mock(Handler.class);
  LogStrategy logStrategy = new DiskLogStrategy(handler);

  logStrategy.log(DEBUG, "tag", "message");

  verify(handler).sendMessage(handler.obtainMessage(DEBUG, "message"));
}
 
Example 42
Project: GravityBox   File: ModLedControl.java   Source Code and License 5 votes vote down vote up
private static void performActiveScreen() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            long ident = Binder.clearCallingIdentity();
            try {
                XposedHelpers.callMethod(mPm, "wakeUp", SystemClock.uptimeMillis());
                mScreenOnDueToActiveScreen = true;
            } finally {
                Binder.restoreCallingIdentity(ident);
            }
        }
    }, 1000);
}
 
Example 43
Project: androidpack   File: EndlessRecyclerViewAdapter_Sample.java   Source Code and License 5 votes vote down vote up
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
  super.onViewCreated(view, savedInstanceState);

  recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

  final SampleEndlessRecyclerViewAdapter adapter = new SampleEndlessRecyclerViewAdapter(R.layout.view_progress, 1);
  adapter.setupScrollListenerToRecyclerView(recyclerView);
  adapter.setLoadMoreListener(new OnLoadMoreListener() {
    @Override
    public void onLoadMore() {
      final Handler handler = new Handler();
      handler.postDelayed(new Runnable() {
        @Override
        public void run() {
          ItemModel itemModel = adapter;
          adapter.addAllItems(StringDummy.get(itemModel.getItemSize()));
          adapter.setLoading(false);

          if (itemModel.getItemSize() > 150) {
            adapter.setLoadingEnabled(false);
          }
        }
      }, 1000);
    }
  });
  recyclerView.setAdapter(adapter);
}
 
Example 44
Project: AndroidBackendlessChat   File: ChatBubbleImageView.java   Source Code and License 5 votes vote down vote up
@Override
public void run() {

    Bitmap b;
    if (!VolleyUtils.getBitmapCache().contains(VolleyUtils.BitmapCache.getCacheKey(path)))
    {
        b = ImageUtils.getCompressed(path,
                BDefines.ImageProperties.MAX_IMAGE_THUMBNAIL_SIZE,
                BDefines.ImageProperties.MAX_IMAGE_THUMBNAIL_SIZE);

        if (b != null)
            VolleyUtils.getBitmapCache().put(VolleyUtils.BitmapCache.getCacheKey(path), b);
    }
    else b =  VolleyUtils.getBitmapCache().getBitmap(VolleyUtils.BitmapCache.getCacheKey(path));

    if (b == null)
    {
        if (loadDone != null)
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    loadDone.onDone();
                }
            });

        return;
    }

    if (isKilled)
        return;

    // Create a new task to fix the image size.
    fixImageAsyncTask = new FixImageAsyncTask(loadDone, path, width, height, false);
    fixImageAsyncTask.execute(b);
}
 
Example 45
Project: CCDownload   File: ADMediaPlayActivity.java   Source Code and License 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 46
Project: asaf-project   File: Board.java   Source Code and License 5 votes vote down vote up
public Board(WorkMode workMode, SystemTimeWrapper systemTimeWrapper) {
    super(WorkMode.SYNCHRONOUS);
    this.workMode = Affirm.notNull(workMode);
    this.systemTimeWrapper = Affirm.notNull(systemTimeWrapper);

    tickHandler = new Handler();

    restart();
}
 
Example 47
Project: FTC2016   File: Camera2Renderer.java   Source Code and License 5 votes vote down vote up
private void startBackgroundThread() {
    Log.i(LOGTAG, "startBackgroundThread");
    stopBackgroundThread();
    mBackgroundThread = new HandlerThread("CameraBackground");
    mBackgroundThread.start();
    mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
 
Example 48
Project: DroidPlugin   File: MyContentProvider1.java   Source Code and License 5 votes vote down vote up
private void showMsg(final String msg) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
        }
    });
    Log.e(TAG, msg);
}
 
Example 49
Project: Hitalk   File: BlackboardFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case BlackboardFragmentLayout.TYPE_PULLREFRESH:
                case BlackboardFragmentLayout.TYPE_LOADREFRESH:
                        loadData(msg.what);
                    break;
            }
        }
    };
}
 
Example 50
Project: GitHub   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Countly.sharedInstance()
                .init(this, COUNTLY_SERVER_URL, COUNTLY_APP_KEY)
                .initMessaging(this, MainActivity.class, COUNTLY_MESSAGING_PROJECT_ID, Countly.CountlyMessagingMode.TEST);
//                .setLocation(LATITUDE, LONGITUDE);
//                .setLoggingEnabled(true);

        Countly.sharedInstance().recordEvent("test", 1);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Countly.sharedInstance().recordEvent("test2", 1, 2);
            }
        }, 5000);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Countly.sharedInstance().recordEvent("test3");
            }
        }, 10000);

    }
 
Example 51
Project: kognitivo   File: ProgressOutputStream.java   Source Code and License 5 votes vote down vote up
private void reportBatchProgress() {
    if (batchProgress > lastReportedProgress) {
        for (GraphRequestBatch.Callback callback : requests.getCallbacks()) {
            if (callback instanceof GraphRequestBatch.OnProgressCallback) {
                final Handler callbackHandler = requests.getCallbackHandler();

                // Keep copies to avoid threading issues
                final GraphRequestBatch.OnProgressCallback progressCallback =
                        (GraphRequestBatch.OnProgressCallback) callback;
                if (callbackHandler == null) {
                    progressCallback.onBatchProgress(requests, batchProgress, maxProgress);
                }
                else {
                    callbackHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            progressCallback.onBatchProgress(
                                    requests,
                                    batchProgress,
                                    maxProgress);
                        }
                    });
                }
            }
        }

        lastReportedProgress = batchProgress;
    }
}
 
Example 52
Project: xwallet   File: SendFragment.java   Source Code and License 5 votes vote down vote up
/**
 *
 * @param inflater
 * @param container
 * @param savedInstanceState
 * @return
 */
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_wallet_send, container, false);
    _clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);

    _sendViewContract = new SendFragmentView(this);
    _handler = new Handler();
    return rootView;
}
 
Example 53
Project: Hitalk   File: TextureVideoView.java   Source Code and License 5 votes vote down vote up
private void init() {
    mContext = getContext();
    mCurrentState = STATE_IDLE;
    mTargetState  = STATE_IDLE;
    mHandler = new Handler();
    mVideoHandler = new Handler(sThread.getLooper(), this);
    setSurfaceTextureListener(this);
}
 
Example 54
Project: react-native-leancloud-sdk   File: RNPushNotificationRegistrationService.java   Source Code and License 5 votes vote down vote up
private void initAVSDK() {
    // We need to run this on the main thread, as the React code assumes that is true.
    // Namely, DevServerHelper constructs a Handler() without a Looper, which triggers:
    // "Can't create handler inside thread that has not called Looper.prepare()"
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        public void run() {
            // 初始化应用信息
            AVOSCloud.initialize(getApplication().getApplicationContext(), leancloudAppId, leancloudAppKey);
            // 启用崩溃错误统计
            AVAnalytics.enableCrashReport(getApplication().getApplicationContext(), true);
            AVOSCloud.setLastModifyEnabled(true);
            AVOSCloud.setDebugLogEnabled(true);

            Context context = getApplication().getApplicationContext();
            Intent pushService = new Intent(context, PushService.class);
            context.startService(pushService);

            //必须要设置默认的通知回调或者订阅一个频道,否则接收不到通知
            mRNPushNotificationHelper = new RNPushNotificationHelper(getApplication());
            PushService.setDefaultPushCallback(getApplication().getApplicationContext(), mRNPushNotificationHelper.getMainActivityClass());
            //this.subscribeChannel("public");

            // 保存 installation 到服务器
            AVInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
                public void done(AVException e) {
                    String installationId = AVInstallation.getCurrentInstallation().getInstallationId();
                    sendRegistrationToken(installationId);
                }
            });


        }
    });
}
 
Example 55
Project: Expert-Android-Programming   File: AddReviewActivity.java   Source Code and License 5 votes vote down vote up
public void onEvent(ImageUploadItem item) {
    MyLg.e(TAG, "Image Complete Received");
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            updateComplete();
        }
    }, 200);

}
 
Example 56
Project: VideoCRE   File: HwAvcEncoder.java   Source Code and License 5 votes vote down vote up
public HwAvcEncoder(final VideoConfig videoConfig, final MediaCodecCallback... callbacks) {
    mVideoConfig = videoConfig;
    mMediaCodecThread = new HandlerThread("HwAvcEncoderThread");
    mMediaCodecThread.start();
    mMediaCodecHandler = new Handler(mMediaCodecThread.getLooper());
    mVideoEncoder = new MediaCodecVideoEncoder();
    mMediaCodecCallbacks = Arrays.asList(callbacks);
}
 
Example 57
Project: Presenter-Client-Android   File: BluetoothPresenterControlTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test that we can successfully connect to another device.
 */
@Test
public void testConnectedStateSuccess() throws InterruptedException {
    ShadowBluetoothSocket.setTransmittedString(SERVER_VERSION_SUCCESS);

    control = new BluetoothPresenterControl(new Handler() {});
    BluetoothDevice bluetoothDevice = ShadowBluetoothAdapter.getDefaultAdapter()
            .getRemoteDevice(DEVICE_ADDRESS);
    control.connect(bluetoothDevice);
    waitForServiceStateChanged(control, RemoteControl.ServiceState.CONNECTED);
}
 
Example 58
Project: LucaHome-AndroidApplication   File: LoginActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    showProgress(false);

    ObjectChangeFinishedContent result = (ObjectChangeFinishedContent) intent.getSerializableExtra(UserService.UserCheckedFinishedBundle);

    if (!result.Success) {
        Logger.getInstance().Error(TAG, String.format(Locale.getDefault(), "Login failed: %s!", Tools.DecompressByteArrayToString(result.Response)));

        displayErrorSnackBar(Tools.DecompressByteArrayToString(result.Response));

        _passwordView.setError(createErrorText(getString(R.string.error_invalid_password)));
        _userView.setError(createErrorText(getString(R.string.error_invalid_user)));
        _userView.requestFocus();
    } else {
        Snacky.builder()
                .setActivty(LoginActivity.this)
                .setText("Successfully logged in!")
                .setDuration(Snacky.LENGTH_LONG)
                .success()
                .show();

        new Handler().postDelayed(() -> {
            NavigationService.NavigationResult navigationResult = NavigationService.getInstance().GoBack(LoginActivity.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 to BootActivity! Please contact LucaHome support!");
            }
        }, Snacky.LENGTH_LONG);
    }
}
 
Example 59
Project: easyfilemanager   File: HomeFragment.java   Source Code and License 5 votes vote down vote up
public void reloadData(){
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            showData();
        }
    }, 500);
}
 
Example 60
Project: garras   File: CollectionDetailsFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onRefresh() {
    mAdapter.setEnableLoadMore(false);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            loadHttpData(false);
        }
    }, 200);
}