android.os.Handler Java Examples

The following examples show how to use android.os.Handler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MainActivity.java    From VehicleInfoOCR with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onMajorTextUpdate(String majorText){
    if(platesHash.contains(majorText))
        return;

    // new entries
    platesHash.add(majorText);
    platesQueue.add(majorText);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            platesHash.remove(platesQueue.remove());
            updatePlates();
        }
    },30*1000);
    if(platesQueue.size() > NUM_PLATES) {
        platesHash.remove(platesQueue.remove());
    }
    if(vehicleNumber.getText()!=null && vehicleNumber.getText().toString().equals("") && !majorText.equals("")) {
        vehicleNumber.setText(majorText);
    }
    updatePlates();
    Log.d(TAG,"Updated majorText: "+majorText);
}
 
Example #2
Source File: CommentsTimeLineFragment.java    From iBeebo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPageScrollStateChanged(int state) {
    super.onPageScrollStateChanged(state);
    switch (state) {
        case ViewPager.SCROLL_STATE_SETTLING:
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    LongClickableLinkMovementMethod.getInstance().setLongClickable(true);

                }
            }, ViewConfiguration.getLongPressTimeout());
            break;
        default:
            LongClickableLinkMovementMethod.getInstance().setLongClickable(false);
            break;
    }
}
 
Example #3
Source File: WifiScanWorker.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
static void cancelWork(final Context context, final boolean useHandler/*, final Handler _handler*/) {
    //PPApplication.logE("WifiScanWorker.cancelWork", "xxx");

    if (useHandler /*&& (_handler == null)*/) {
        PPApplication.startHandlerThreadPPScanners();
        final Handler handler = new Handler(PPApplication.handlerThreadPPScanners.getLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                _cancelWork(context);
            }
        });
    }
    else {
        _cancelWork(context);
    }
}
 
Example #4
Source File: DeviceScanActivity.java    From BLEConnect with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();

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

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

    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
}
 
Example #5
Source File: MainActivity.java    From HaiNaBaiChuan with Apache License 2.0 6 votes vote down vote up
@Override
    protected void onInit() {
        super.onInit();
        currentFragment = FragmentFactory.newFragment(C.fragment.HOME);
        addFragment(currentFragment, R.id.fragment_container);
        menuHelper = new MenuHelper();
        menuHelper.createMenu(menu, presenter.getMenuData());
        handler = new Handler(Looper.getMainLooper());
        FirHelper.getInstance().checkUpdate(this);
//        NetRequest.Instance().uploadHeadPic(new File("/storage/emulated/0/Download/trim.jpg"));
//        NetRequest.Instance().editSign("求仁而得仁,又何怨 发愤忘食,乐以忘忧,不知老之将至 敬鬼神而远之 子罕言利,与命,与仁", new NetRequest.RequestListener<String>() {
//            @Override
//            public void success(String s) {
//
//            }
//
//            @Override
//            public void error(BmobException err) {
//
//            }
//        });
    }
 
Example #6
Source File: QrcodeUploadActivity.java    From xpay with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    handler = new Handler();
    setContentView(R.layout.activity_qrcode_upload);
    Intent intent = getIntent();
    currentPhotoString = intent.getStringExtra("file");
    ImageView img = findViewById(R.id.image_view);
    img.setImageURI(Uri.fromFile(new File(currentPhotoString)));
    eMoney = findViewById(R.id.txt_money);
    eName = findViewById(R.id.txt_name);
    upButton = findViewById(R.id.btn_upload);
    upButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toUpload();
        }
    });
    loadImage();
}
 
Example #7
Source File: SyncMusic.java    From Kore with Apache License 2.0 6 votes vote down vote up
/**
 * Syncs Audio genres and forwards calls to sync albums:
 * Genres->Albums->Songs
 */
private void chainCallSyncGenres(final SyncOrchestrator orchestrator,
                                 final HostConnection hostConnection,
                                 final Handler callbackHandler,
                                 final ContentResolver contentResolver) {
    final int hostId = hostConnection.getHostInfo().getId();

    // Genres->Albums->Songs
    AudioLibrary.GetGenres action = new AudioLibrary.GetGenres(getGenresProperties);
    action.execute(hostConnection, new ApiCallback<List<LibraryType.DetailsGenre>>() {
        @Override
        public void onSuccess(List<LibraryType.DetailsGenre> result) {
            if (result != null)
                insertGenresItems(hostId, result, contentResolver);

            chainCallSyncAlbums(orchestrator, hostConnection, callbackHandler, contentResolver, 0);
        }

        @Override
        public void onError(int errorCode, String description) {
            // Ok, something bad happend, just quit
            orchestrator.syncItemFailed(errorCode, description);
        }
    }, callbackHandler);
}
 
Example #8
Source File: G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCharacteristicWrite(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
    Log.e(TAG, "OnCharacteristic WRITE started: "
            + getUUIDName(characteristic.getUuid())
            + " status: " + getStatusName(status));
    //Log.e(TAG, "Write Status " + String.valueOf(status));
    //Log.e(TAG, "Characteristic " + String.valueOf(characteristic.getUuid()));

    if (enforceMainThread()) {
        Handler iHandler = new Handler(Looper.getMainLooper());
        iHandler.post(new Runnable() {
            @Override
            public void run() {
                processOnCharacteristicWrite(gatt, characteristic, status);
            }
        });
    } else {
        processOnCharacteristicWrite(gatt, characteristic, status);
    }


}
 
Example #9
Source File: ConcurrencyWithSchedulersDemoFragment.java    From RxJava-Android-Samples with Apache License 2.0 6 votes vote down vote up
private void _log(String logMsg) {

    if (_isCurrentlyOnMainThread()) {
      _logs.add(0, logMsg + " (main thread) ");
      _adapter.clear();
      _adapter.addAll(_logs);
    } else {
      _logs.add(0, logMsg + " (NOT main thread) ");

      // You can only do below stuff on main thread.
      new Handler(Looper.getMainLooper())
          .post(
              () -> {
                _adapter.clear();
                _adapter.addAll(_logs);
              });
    }
  }
 
Example #10
Source File: TestFragment.java    From UcMainPagerDemo with Apache License 2.0 6 votes vote down vote up
private void initView(ViewGroup root) {
    mRecyclerView = (RecyclerView) root.findViewById(R.id.test_recycler);
    mSwipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.refresh_layout);
    mSwipeRefreshLayout.setEnabled(getArguments().getBoolean(REFRESH_SUPPORT));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }, 2000);
        }
    });
}
 
Example #11
Source File: LoadMoreRecyclerFragemnt.java    From meiShi with Apache License 2.0 6 votes vote down vote up
public void showMoreData(final List<T> dataList) {
    int delay = 0;
    if (TimeUtils.getCurrentTime() - currentTime < DEF_DELAY) {
        delay = DEF_DELAY;
    }
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            currentState = STATE_NORMAL;
            if (dataList.isEmpty()) {
                mAdapter.setHasMoreDataAndFooter(false, false);
                getHolder().showMsgInBottom(R.string.msg_no_more_data);
            } else {
                mAdapter.appendToList(dataList);
                currentPage++;
                mAdapter.setHasMoreDataAndFooter(true, false);
            }
            mAdapter.notifyDataSetChanged();
        }
    }, delay);
}
 
Example #12
Source File: IndividualityActivity.java    From MyHearts with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.iv_back:
            finish();
            break;
        case R.id.iv_finish:
            String slognName = mUsercenterSign.getText().toString();
            if (slognName != null && slognName.length() > 0) {
                Toast.makeText(IndividualityActivity.this, slognName, Toast.LENGTH_SHORT).show();
                KeyBoard.closeSoftKeyboard(IndividualityActivity.this);
                PreferencesUtils.saveSlognName(IndividualityActivity.this, slognName);
                Intent intent = new Intent();
                setResult(100, intent);
                new Handler().postDelayed(() -> finish(), 500);
            }
            break;
    }
}
 
Example #13
Source File: BaseService.java    From ShadowsocksRR with Apache License 2.0 6 votes vote down vote up
protected void changeState(final int s, final String msg) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            if (state != s || msg != null) {
                if (callbacksCount > 0) {
                    int n = callbacks.beginBroadcast();
                    for (int i = 0; i < n; i++) {
                        try {
                            callbacks.getBroadcastItem(i).stateChanged(s, binder.getProfileName(), msg);
                        } catch (Exception e) {
                            // Ignore
                        }
                    }
                    callbacks.finishBroadcast();
                }
                state = s;
            }
        }
    });
}
 
Example #14
Source File: SystemUiHelper.java    From EhViewer with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new SystemUiHelper.
 *
 * @param activity The Activity who's system UI should be changed
 * @param level The level of hiding. Should be either {@link #LEVEL_LOW_PROFILE},
 *              {@link #LEVEL_HIDE_STATUS_BAR}, {@link #LEVEL_LEAN_BACK} or
 *              {@link #LEVEL_IMMERSIVE}
 * @param flags Additional options. See {@link #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES} and
 *              {@link #FLAG_IMMERSIVE_STICKY}
 * @param listener A listener which is called when the system visibility is changed
 */
public SystemUiHelper(Activity activity, int level, int flags,
        OnVisibilityChangeListener listener) {

    mHandler = new Handler(Looper.getMainLooper());
    mHideRunnable = new HideRunnable();

    // Create impl
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        mImpl = new SystemUiHelperImplKK(activity, level, flags, listener);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        mImpl = new SystemUiHelperImplJB(activity, level, flags, listener);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        mImpl = new SystemUiHelperImplICS(activity, level, flags, listener);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mImpl = new SystemUiHelperImplHC(activity, level, flags, listener);
    } else {
        mImpl = new SystemUiHelperImplBase(activity, level, flags, listener);
    }
}
 
Example #15
Source File: TransactionHistoryFragment.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void initTransactionHistoryRecycler() {
    TransHistoryAdapter adapter = new TransHistoryAdapter();
    new Handler();
    adapter.setItemClickListener(new TransHistoryAdapter.OnItemClickListener() {
        @Override
        public void OnItemClick(int position) {
            Intent detailsIntent = new Intent(getActivity(), TransactionDetailsActivity.class);
            detailsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            detailsIntent.putExtra(EXTRA_TRANSACTION_POSITION, position);
            startActivity(detailsIntent);
            getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.no_slide);
        }
    });

    final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    rvTransactionsList.setLayoutManager(layoutManager);
    rvTransactionsList.setAdapter(adapter);

}
 
Example #16
Source File: Timber4.java    From Muzesto with GNU General Public License v3.0 6 votes vote down vote up
private void initRecorder() {
    final int bufferSize = 2 * AudioRecord.getMinBufferSize(RECORDER_SAMPLE_RATE,
            RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
    audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, RECORDER_SAMPLE_RATE,
            RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize);
    AudioUtil.initProcessor(RECORDER_SAMPLE_RATE, RECORDER_CHANNELS, RECORDER_ENCODING_BIT);

    recordingThread = new Thread("recorder") {
        @Override
        public void run() {
            super.run();
            buffer = new byte[bufferSize];
            Looper.prepare();
            audioRecord.setRecordPositionUpdateListener(recordPositionUpdateListener, new Handler(Looper.myLooper()));
            int bytePerSample = RECORDER_ENCODING_BIT / 8;
            float samplesToDraw = bufferSize / bytePerSample;
            audioRecord.setPositionNotificationPeriod((int) samplesToDraw);
            //We need to read first chunk to motivate recordPositionUpdateListener.
            //Mostly, for lower versions - https://code.google.com/p/android/issues/detail?id=53996
            audioRecord.read(buffer, 0, bufferSize);
            Looper.loop();
        }
    };
}
 
Example #17
Source File: YouTubePlayerController.java    From react-native-youtube with MIT License 5 votes vote down vote up
public void onVideoFragmentResume() {
    if (isResumePlay() && mYouTubePlayer != null) {
        // For some reason calling mYouTubePlayer.play() right away is ineffective
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
               mYouTubePlayer.play();
            }
        }, 1);
    }
}
 
Example #18
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
        IntentFilter filter, String broadcastPermission, Handler scheduler) {
    if (receiver == null) {
        // Allow retrieving current sticky broadcast; this is safe since we
        // aren't actually registering a receiver.
        return super.registerReceiverAsUser(null, user, filter, broadcastPermission, scheduler);
    } else {
        throw new ReceiverCallNotAllowedException(
                "BroadcastReceiver components are not allowed to register to receive intents");
    }
}
 
Example #19
Source File: QosInfoThread.java    From KSYMediaPlayer_Android with Apache License 2.0 5 votes vote down vote up
public QosInfoThread(Context context, Handler handler) {
    mHandler = handler;
    mCpuStats = new CpuInfo();
    mi = new Debug.MemoryInfo();
    mRunning = true;
    mQosObject = new QosBean();
    if(context != null)
        mPackageName = context.getPackageName();
}
 
Example #20
Source File: IMESetupWizardActivity.java    From brailleback with Apache License 2.0 5 votes vote down vote up
@Override
public void onResume() {
  super.onResume();
  // Try to call showInputMethodPicker() without button click.
  // Need delay to ensure showInputMethodPicker() receives correct UID, else it fails.
  Handler handler = new Handler();
  handler.postDelayed(
      new Runnable() {
        @Override
        public void run() {
          inputMethodManager.showInputMethodPicker();
        }
      },
      300);
}
 
Example #21
Source File: BitmapDecodeWorkerTask.java    From AntennaPodSP with MIT License 5 votes vote down vote up
public BitmapDecodeWorkerTask(Handler handler, ImageView target,
                              ImageWorkerTaskResource imageResource, int length, int imageType) {
    super();
    this.handler = handler;
    this.target = target;
    this.imageResource = imageResource;
    this.PREFERRED_LENGTH = length;
    this.imageType = imageType;
    this.defaultCoverResource = android.R.color.transparent;
}
 
Example #22
Source File: StopCallback.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public StopCallback(Service paramService, Handler paramHandler, Boolean paramBoolean,
        int paramInt) {
    super(paramService);
    this.handler = paramHandler;
    this.isRePlay = paramBoolean;
    this.type = paramInt;
}
 
Example #23
Source File: SmartHandler.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Constructs a SmartHandler */
public SmartHandler(@Nullable Executor executor) {
  this.executor = executor;
  if (this.executor == null) {
    if (!testMode) {
      handler = new Handler(Looper.getMainLooper());
    } else {
      handler = null; // we will call back on the thread pool.
    }
  } else {
    handler = null;
  }
}
 
Example #24
Source File: MainActivity.java    From MISportsConnectWidget with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LogUtils.setLogLevel(LogUtils.LOG_LEVEL_DEBUG);

    final MISportsConnectView miSportsConnectView = (MISportsConnectView) findViewById(R.id.mi_sports_loading_view);

    SportsData sportsData = new SportsData();
    sportsData.step = 2714;
    sportsData.distance = 1700;
    sportsData.calories = 34;
    sportsData.progress = 75;
    miSportsConnectView.setSportsData(sportsData);

    handler = new Handler();
    final Button connectButton = (Button) findViewById(R.id.connect_button);
    connectButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    connect = !connect;
                    miSportsConnectView.setConnected(connect);
                    connectButton.setText(connect? getString(R.string.disconnect) : getString(R.string.connect));
                }
            }, 500);
        }
    });
}
 
Example #25
Source File: MainActivity.java    From PeopleSegmentationDemo with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    requestMultiplePermissions();

    btn = (Button) findViewById(R.id.btn);
    imageView = (ImageView)findViewById(R.id.image_view);
    infoTextView = (TextView)findViewById(R.id.info_text);

    HandlerThread thread = new HandlerThread("initThread");
    thread.start();
    runThread = new Handler(thread.getLooper());

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showPictureDialog();
        }
    });

    inProgressDialog = new AlertDialog
            .Builder(this, R.style.Theme_AppCompat_DayNight_Dialog_Alert)
            .setTitle("Running...")
            .setView(R.layout.progress_bar)
            .create();

    storagePath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + STORAGE_DIRECTORY;
    File file = new File(storagePath);
    if (!file.exists()) {
        file.mkdirs();
    }
    initMace();
}
 
Example #26
Source File: LoadAndDisplayImageTask.java    From WliveTV with Apache License 2.0 5 votes vote down vote up
static void runTask(Runnable r, boolean sync, Handler handler, ImageLoaderEngine engine) {
	if (sync) {
		r.run();
	} else if (handler == null) {
		engine.fireCallback(r);
	} else {
		handler.post(r);
	}
}
 
Example #27
Source File: SyncCustomizationFragment.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    if (preference == mSyncEverything) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                updateDataTypeState();
            }
        });
        return true;
    }
    if (isSyncTypePreference(preference)) {
        final boolean syncAutofillToggled = preference == mSyncAutofill;
        final boolean preferenceChecked = (boolean) newValue;
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                if (syncAutofillToggled) {
                    // If the user checks the autofill sync checkbox, then enable and check the
                    // payments integration checkbox.
                    //
                    // If the user unchecks the autofill sync checkbox, then disable and uncheck
                    // the payments integration checkbox.
                    mPaymentsIntegration.setEnabled(preferenceChecked);
                    mPaymentsIntegration.setChecked(preferenceChecked);
                }
                maybeDisableSync();
            }
        });
        return true;
    }
    return false;
}
 
Example #28
Source File: SplashLoadingService.java    From VoIpUSSD with Apache License 2.0 5 votes vote down vote up
@Override
public void onDestroy() {
    super.onDestroy();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (layout != null) {
                wm.removeView(layout);
                layout = null;
            }
        }
    },500);
}
 
Example #29
Source File: ConversationStickerViewModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private ConversationStickerViewModel(@NonNull Application application, @NonNull StickerSearchRepository repository) {
  this.application           = application;
  this.repository            = repository;
  this.stickers              = new MutableLiveData<>();
  this.stickersAvailable     = new MutableLiveData<>();
  this.availabilityThrottler = new Throttler(500);
  this.packObserver          = new ContentObserver(new Handler()) {
    @Override
    public void onChange(boolean selfChange) {
      availabilityThrottler.publish(() -> repository.getStickerFeatureAvailability(stickersAvailable::postValue));
    }
  };

  application.getContentResolver().registerContentObserver(DatabaseContentProviders.StickerPack.CONTENT_URI, true, packObserver);
}
 
Example #30
Source File: AccessTokenManager.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
void refreshCurrentAccessToken() {
    if (Looper.getMainLooper().equals(Looper.myLooper())) {
        refreshCurrentAccessTokenImpl();
    } else {
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                refreshCurrentAccessTokenImpl();
            }
        });
    }
}