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: 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 #2
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 #3
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 #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: 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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: Animation.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the handler used to invoke listeners.
 *
 * @hide
 */
public void setListenerHandler(Handler handler) {
    if (mListenerHandler == null) {
        mOnStart = new Runnable() {
            public void run() {
                if (mListener != null) {
                    mListener.onAnimationStart(Animation.this);
                }
            }
        };
        mOnRepeat = new Runnable() {
            public void run() {
                if (mListener != null) {
                    mListener.onAnimationRepeat(Animation.this);
                }
            }
        };
        mOnEnd = new Runnable() {
            public void run() {
                if (mListener != null) {
                    mListener.onAnimationEnd(Animation.this);
                }
            }
        };
    }
    mListenerHandler = handler;
}
 
Example #18
Source File: WelcomeActivity.java    From AndroidObjectDetection-OpenCV with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent welcome = new Intent(WelcomeActivity.this, CameraActivity.class);
            startActivity(welcome);
            finish();
        }
    },SPLASH_TIME);
}
 
Example #19
Source File: DefaultDrmSessionManager.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @deprecated Use {@link #newWidevineInstance(MediaDrmCallback, HashMap)} and {@link
 *     #addListener(Handler, DefaultDrmSessionEventListener)}.
 */
@Deprecated
public static DefaultDrmSessionManager<FrameworkMediaCrypto> newWidevineInstance(
    MediaDrmCallback callback,
    HashMap<String, String> optionalKeyRequestParameters,
    Handler eventHandler,
    DefaultDrmSessionEventListener eventListener)
    throws UnsupportedDrmException {
  DefaultDrmSessionManager<FrameworkMediaCrypto> drmSessionManager =
      newWidevineInstance(callback, optionalKeyRequestParameters);
  if (eventHandler != null && eventListener != null) {
    drmSessionManager.addListener(eventHandler, eventListener);
  }
  return drmSessionManager;
}
 
Example #20
Source File: Camera2Renderer.java    From FtcSamples with MIT 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 #21
Source File: WebSocketClient.java    From SoloPi with Apache License 2.0 5 votes vote down vote up
public WebSocketClient(URI uri, Listener listener, List<BasicNameValuePair> extraHeaders) {
    mURI          = uri;
    mListener = listener;
    mExtraHeaders = extraHeaders;
    mParser       = new HybiParser(this);

    mHandlerThread = new HandlerThread("websocket-thread");
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());
}
 
Example #22
Source File: JavaCamera2View.java    From pasm-yolov3-Android with GNU General Public License v3.0 5 votes vote down vote up
private void startBackgroundThread() {
    Log.i(LOGTAG, "startBackgroundThread");
    stopBackgroundThread();
    mBackgroundThread = new HandlerThread("OpenCVCameraBackground");
    mBackgroundThread.start();
    mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
 
Example #23
Source File: VideoCastControllerFragment.java    From android with Apache License 2.0 5 votes vote down vote up
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    sDialogCanceled = false;
    mCastController = (IVideoCastController) activity;
    mHandler = new Handler();
    try {
        mCastManager = VideoCastManager.getInstance(activity);
    } catch (CastException e) {
        // logged already
    }
}
 
Example #24
Source File: BatteryService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public BatteryService(Context context) {
    super(context);

    mContext = context;
    mHandler = new Handler(true /*async*/);
    mLed = new Led(context, getLocalService(LightsManager.class));
    mBatteryStats = BatteryStatsService.getService();
    mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);

    mCriticalBatteryLevel = mContext.getResources().getInteger(
            com.android.internal.R.integer.config_criticalBatteryWarningLevel);
    mLowBatteryWarningLevel = mContext.getResources().getInteger(
            com.android.internal.R.integer.config_lowBatteryWarningLevel);
    mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
            com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
    mShutdownBatteryTemperature = mContext.getResources().getInteger(
            com.android.internal.R.integer.config_shutdownBatteryTemperature);

    mBatteryLevelsEventQueue = new ArrayDeque<>();
    mMetricsLogger = new MetricsLogger();

    // watch for invalid charger messages if the invalid_charger switch exists
    if (new File("/sys/devices/virtual/switch/invalid_charger/state").exists()) {
        UEventObserver invalidChargerObserver = new UEventObserver() {
            @Override
            public void onUEvent(UEvent event) {
                final int invalidCharger = "1".equals(event.get("SWITCH_STATE")) ? 1 : 0;
                synchronized (mLock) {
                    if (mInvalidCharger != invalidCharger) {
                        mInvalidCharger = invalidCharger;
                    }
                }
            }
        };
        invalidChargerObserver.startObserving(
                "DEVPATH=/devices/virtual/switch/invalid_charger");
    }
}
 
Example #25
Source File: VLCObject.java    From libvlc-sdk-android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set an event listener and an executor Handler
 *
 * @param listener see {@link VLCEvent.Listener}
 * @param handler  Handler in which events are sent. If null, a handler will be created running on the main thread
 */
protected synchronized void setEventListener(VLCEvent.Listener<T> listener, Handler handler) {
    if (mHandler != null)
        mHandler.removeCallbacksAndMessages(null);
    mEventListener = listener;
    if (mEventListener == null)
        mHandler = null;
    else if (mHandler == null)
        mHandler = handler != null ? handler : new Handler(Looper.getMainLooper());
}
 
Example #26
Source File: ReplayLocationDispatcherTest.java    From graphhopper-navigation-android with MIT License 5 votes vote down vote up
@Test
public void checksStopDispatchingWhenStop() {
  List<Location> anyLocations = mock(List.class);
  Handler aHandler = mock(Handler.class);
  ReplayLocationDispatcher theReplayLocationDispatcher = new ReplayLocationDispatcher(anyLocations, aHandler);

  theReplayLocationDispatcher.stop();

  verify(aHandler, times(1)).removeCallbacks(eq(theReplayLocationDispatcher));
}
 
Example #27
Source File: G5CollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void connectToDevice(BluetoothDevice device) {
    if (JoH.ratelimit("G5connect-rate", 2)) {

        Log.d(TAG, "connectToDevice() start");
        if (mGatt != null) {
            Log.i(TAG, "BGatt isnt null, Closing.");
            try {
                mGatt.close();
            } catch (NullPointerException e) {
                // concurrency related null pointer
            }
            mGatt = null;
        }
        Log.i(TAG, "Request Connect");
        final BluetoothDevice mDevice = device;
        if (enforceMainThread()) {
            Handler iHandler = new Handler(Looper.getMainLooper());
            iHandler.post(new Runnable() {
                @Override
                public void run() {
                    connectGatt(mDevice);
                }
            });
        } else {
            connectGatt(mDevice);
        }

    } else {
        Log.e(TAG, "connectToDevice baulking due to rate-limit");
    }
}
 
Example #28
Source File: TimerManager.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
public TimerTask(final Handler handler, final int what, final long delay, final long period, final int triggerLimit) {
    this.handler = handler;
    this.notifyWhat = what;
    this.delay = delay;
    this.period = period;
    this.triggerLimit = triggerLimit;
}
 
Example #29
Source File: DecodeThread.java    From moVirt with Apache License 2.0 5 votes vote down vote up
Handler getHandler() {
    try {
        handlerInitLatch.await();
    } catch (InterruptedException ie) {
        // continue?
    }
    return handler;
}
 
Example #30
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);
    }
}