下面列出了android.os.Handler#postDelayed ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onCreate()
{
super.onCreate();
handler = new Handler();
runnable = () ->
{
handler.postDelayed(runnable, 60000);
Utilities.stageQueue.postRunnable(() ->
{
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++)
{
LocationController.getInstance(a).update();
}
});
};
handler.postDelayed(runnable, 60000);
}
public void startHandler(View view) {
if(!handlerStarted) {
if (!isConnected()) {
doConnect();
Handler handler = new Handler();
handler.postDelayed(() -> {
handler1.post(process);
handler.post(runnableMeta);
}, 5000);
} else {
handler1.post(process);
handler.post(runnableMeta);
}
startHandlerButton.setText("Stop Handler");
handlerStarted=true;
}
else{
stopHandler();
handlerStarted=false;
}
}
public PDelay(AppRunner appRunner, final int delay, final DelayCB callbackkfn) {
mAppRunner = appRunner;
handler = new Handler();
mCallbackfn = callbackkfn;
this.delay = delay;
Runnable task = new Runnable() {
@Override
public void run() {
if (mCancelJob) return;
callbackkfn.event();
handler.removeCallbacks(this);
}
};
handler.postDelayed(task, delay);
mAppRunner.whatIsRunning.add(this);
}
public void play(int start, PlayDirection direction) {
if (mPlaying)
return;
mTotal = mPlayable.getTotal();
if (mTotal <= 1) {
return;
}
mPlaying = true;
playTo(start);
final Handler handler = new Handler(Looper.myLooper());
mTimerTask = new Runnable() {
@Override
public void run() {
if (!mPaused) {
playNextFrame();
}
if (mPlaying) {
handler.postDelayed(mTimerTask, mTimeInterval);
}
}
};
handler.postDelayed(mTimerTask, mTimeInterval);
}
public void sync() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
updateTime();
}
}, 500);
// Register a broadcast handler to use for the alarm Intent
// Also listen for TIME_CHANGED and TIMEZONE_CHANGED events
mSReceiver = new TimeSyncReqReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(TIME_SYNC_INTENT);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
mCtx.registerReceiver(mSReceiver, filter);
// register an alarm to sync the time once a day
Intent alarmIntent = new Intent(TIME_SYNC_INTENT);
alarmPendingIntent = PendingIntent.getBroadcast(mCtx, 0, alarmIntent, 0);
alarmMgr = (AlarmManager) mCtx.getSystemService(Context.ALARM_SERVICE);
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, alarmPendingIntent);
}
private void insertIntoList(WifiObject wifi) {
wifiArrayAdapter.add(wifi);
final ProgressDialog progress = new ProgressDialog(getActivity());
progress.setTitle("Learning");
progress.setMessage("Please wait while we are collecting the Wifi APs around you...");
progress.setCanceledOnTouchOutside(false);
progress.show();
Runnable progressRunnable = new Runnable() {
@Override
public void run() {
progress.cancel();
handler.removeCallbacks(runnableCode);
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, learnPeriodVal * 60 * 1000);
}
/**
* Helper method to print out the lifecycle state of each Activity. Note this has
* been wrapped in a Handler to delay the output due to overlaps in lifecycle state
* changes as one Activity launches another.
* @link http://developer.android.com/guide/topics/fundamentals/activities.html#CoordinatingActivities
* @param viewMethods TextView to list out the lifecycle methods called
* @param viewStatus TextView to list out the status of all Activity classes
*/
public static void printStatus(final TextView viewMethods, final TextView viewStatus) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Get the stack of Activity lifecycle methods called and print to TextView
StringBuilder sbMethods = new StringBuilder();
List<String> listMethods = mStatusTracker.getMethodList();
for (String method : listMethods) {
sbMethods.insert(0, method + "\r\n");
}
if(viewMethods != null) {
viewMethods.setText(sbMethods.toString());
}
// Get the status of all Activity classes and print to TextView
StringBuilder sbStatus = new StringBuilder();
for (String key : mStatusTracker.keySet()) {
sbStatus.insert(0,key + ": " + mStatusTracker.getStatus(key) + "\n");
}
if(viewStatus != null) {
viewStatus.setText(sbStatus.toString());
}
}
}, 750);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
final DatabaseHelper dbHelper = new DatabaseHelper(this);
final AlphaAnimation alpha = new AlphaAnimation(1,0);
alpha.setDuration(200);
final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeSplash);
final Handler handler = new Handler();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
relativeLayout.setAnimation(alpha);
}
}, 700);
handler.postDelayed(new Runnable() {
@Override
public void run() {
final Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
}
}, DURATION);
}
@Override
public void onTitleClick() {
toggleExpandingElement(mEntry, mViewHolder.contentLayout);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mItemClickListener != null) {
mItemClickListener.onExpandedClick(mEntry);
}
}
}, 300);
}
private void startAnimationThreadStuff(long delay) {
if (updateThread != null && updateThread.isAlive())
updateThread.interrupt();
// Start animation after a delay so there's no missed frames while the app loads up
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(!progressView.isIndeterminate()) {
progressView.setProgress(0f);
// Run thread to update progress every quarter second until full
updateThread = new Thread(new Runnable() {
@Override
public void run() {
while (progressView.getProgress() < progressView.getMaxProgress() && !Thread.interrupted()) {
// Must set progress in UI thread
handler.post(new Runnable() {
@Override
public void run() {
progressView.setProgress(progressView.getProgress() + 10);
}
});
SystemClock.sleep(250);
}
}
});
updateThread.start();
}
// Alias for resetAnimation, it's all the same
progressView.startAnimation();
}
}, delay);
}
private void startBluetoothDiscovery() {
deviceListView.removeAllViews();
foundDevices.clear();
central = new BluetoothCentral(getContext(), bluetoothCentralCallback, new Handler(Looper.getMainLooper()));
central.scanForPeripherals();
txtSearching.setVisibility(View.VISIBLE);
txtSearching.setText(R.string.label_bluetooth_searching);
progressBar.setVisibility(View.VISIBLE);
progressHandler = new Handler();
// Don't let the BLE discovery run forever
progressHandler.postDelayed(new Runnable() {
@Override
public void run() {
stopBluetoothDiscovery();
txtSearching.setText(R.string.label_bluetooth_searching_finished);
progressBar.setVisibility(View.GONE);
BluetoothDeviceView notSupported = new BluetoothDeviceView(context);
notSupported.setDeviceName(getString(R.string.label_scale_not_supported));
notSupported.setSummaryText(getString(R.string.label_click_to_help_add_support));
notSupported.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent notSupportedIntent = new Intent(Intent.ACTION_VIEW);
notSupportedIntent.setData(
Uri.parse("https://github.com/oliexdev/openScale/wiki/Supported-scales-in-openScale"));
startActivity(notSupportedIntent);
}
});
deviceListView.addView(notSupported);
}
}, 20 * 1000);
}
private SelfCancelingListener(LocationManager manager) {
mLocationManager = manager;
mHandler = new Handler();
mCancelRunnable = new Runnable() {
@Override
public void run() {
mLocationManager.removeUpdates(SelfCancelingListener.this);
sListener = null;
}
};
mHandler.postDelayed(mCancelRunnable, REQUEST_TIMEOUT_MS);
}
@NonNull
@Override
public Result doWork() {
try {
//PPApplication.logE("AvoidRescheduleReceiverWorker.doWork", "xxx");
PPApplication.startHandlerThreadPPScanners();
final Handler handler = new Handler(PPApplication.handlerThreadPPScanners.getLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
enqueueWork();
}
}, 500);
return Result.success();
} catch (Exception e) {
//Log.e("AvoidRescheduleReceiverWorker.doWork", Log.getStackTraceString(e));
PPApplication.recordException(e);
/*Handler _handler = new Handler(getApplicationContext().getMainLooper());
Runnable r = new Runnable() {
public void run() {
android.os.Process.killProcess(android.os.Process.myPid());
}
};
_handler.postDelayed(r, 1000);*/
return Result.failure();
}
}
public void shuffle() {
final Handler handler = new Handler();
handler.postDelayed(() -> {
MusicPlayerRemote.openQueue(mData,0,true);
//MusicPlayer.playAll(mContext, getRealSongIds(), 0, -1, Util.IdType.NA, false);
randommize();
},100);
}
private void checkDelayed() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if (arePermissionsGranted())
startService();
else
checkDelayed();
}
}, 1000);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//makes Window Fullscreen and show ontop of the Lockscreen
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getSupportActionBar().hide();
setContentView(R.layout.activity_receiverpictureactivity);
Window wind = this.getWindow();
wind.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
wind.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (savedInstanceState != null) {
if (savedInstanceState.getBoolean("ready", false)) {
page = savedInstanceState.getInt("pageItem", 0);
screenislocked();
}
}
RateThisApp.onCreate(this);
RateThisApp.showRateDialogIfNeeded(this);
//periodically checks if the screen is locked, if it is calls screenislocked()
handly = new Handler();
goahead = new Runnable() {
@Override
public void run() {
KeyguardManager myKM = (KeyguardManager) getApplication().getSystemService(Context.KEYGUARD_SERVICE);
if (myKM != null) {
if( myKM.inKeyguardRestrictedInputMode()) {
screenislocked();
} else {
handly.postDelayed(goahead, 40);
}
} else {
handly.postDelayed(goahead, 40);
}
}
};
goahead.run();
}
/**
* @param context Context of the app
* @param event Event to notify
* @param eventsUsers EventUser associated with this event
* @param activeAction If actions will be shown
* @param autoCancel If force notification to auto-cancel in 5s (after subscription)
*/
public static void notify(final Context context, final Events event, EventsUsers eventsUsers, boolean activeAction, boolean autoCancel) {
Intent notificationIntent = EventActivity.getIntent(context, event);
PendingIntent intent = PendingIntent.getActivity(context, event.id, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final NotificationCompat.Builder notificationBuilder = getBaseNotification(context)
.setContentTitle(event.name.trim())
.setContentText(event.description.replace('\n', ' '))
.setWhen(event.beginAt.getTime())
.setStyle(new NotificationCompat.BigTextStyle().bigText(event.description))
.setGroup(context.getString(R.string.notifications_events_unique_id))
.setChannelId(context.getString(R.string.notifications_events_unique_id))
.setContentIntent(intent);
if (event.kind != null)
notificationBuilder.setSubText(event.kind.name());
if (autoCancel) {
notificationBuilder.addAction(R.drawable.ic_event_black_24dp, context.getString(R.string.notification_auto_clear), null);
Handler h = new Handler();
long delayInMilliseconds = 5000;
h.postDelayed(() -> NotificationManagerCompat.from(context).cancel(context.getString(R.string.notifications_events_unique_id), event.id), delayInMilliseconds);
} else if (activeAction) {
Intent notificationIntentAction = new Intent(context, IntentEvent.class);
if (eventsUsers != null) {
notificationIntentAction.putExtra(IntentEvent.ACTION, IntentEvent.ACTION_DELETE);
notificationIntentAction.putExtra(IntentEvent.CONTENT_EVENT_USER_ID, eventsUsers.id);
notificationIntentAction.putExtra(IntentEvent.CONTENT_EVENT_ID, eventsUsers.eventId);
} else {
notificationIntentAction.putExtra(IntentEvent.ACTION, IntentEvent.ACTION_CREATE);
notificationIntentAction.putExtra(IntentEvent.CONTENT_EVENT_ID, event.id);
}
// intentEvent.putExtra(EventActivity.ARG_EVENT, ServiceGenerator.getGson().toJson(event));
PendingIntent intentAction = PendingIntent.getService(context, 1000000 + event.id, notificationIntentAction, PendingIntent.FLAG_UPDATE_CURRENT);
if (eventsUsers == null) {
notificationBuilder.addAction(R.drawable.ic_event_black_24dp, context.getString(R.string.event_subscribe), intentAction);
} else if (!event.beginAt.after(new Date()))
notificationBuilder.addAction(R.drawable.ic_event_black_24dp, context.getString(R.string.event_unsubscribe), null);
else
notificationBuilder.addAction(R.drawable.ic_event_black_24dp, context.getString(R.string.event_unsubscribe), intentAction);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setCategory(Notification.CATEGORY_EVENT);
}
Notification notification = notificationBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManagerCompat.from(context).notify(context.getString(R.string.notifications_events_unique_id), event.id, notification);
}
/**
* Gets the node from the matching list by position and visit all it's ancestors, including
* itself, to find the first visible and focusable target node. And perform focus on the target
* node. If not found, post-delay some time to try again until reaching the retry limit.
*
* <p>: [Screen Search] The nodes, which are covered by software IME, are invisible at
* the moment of closing IME.
*
* @param position the index value in the matched list.
*/
private void postPerformFocusNode(int position) {
final AccessibilityNode clickedNode = searchState.getResult(position).node();
if (clickedNode.isWebContainer()) {
// Since we are able to find nodes outside of current screen for webView, we need to
// ensure the selected node is in current screen so we could focus on it.
clickedNode.showOnScreen(EVENT_ID_UNTRACKED);
}
final Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
int counter = 0;
int counterLimit = 20;
// The clickedNode is one of the nodes in the node cache, will be recycled when hide() API
// been called, don't need to be recycled here.
@Override
public void run() {
// Finding clickNodes's matching ancestor or self.
AccessibilityNode focusableVisibleNode =
clickedNode.getSelfOrMatchingAncestor(
AccessibilityNodeInfoUtils.FILTER_SHOULD_FOCUS);
if (focusableVisibleNode != null) {
// Set focus on the matching node.
focusableVisibleNode.performAction(
AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null);
// Recycle focusableNode.
AccessibilityNode.recycle(
"SearchScreenOverlay.postPerformFocusNode()", focusableVisibleNode);
// Close search UI.
hide();
} else {
// Can not found a focusable visible node, post-delay to try again later or set as
// the clicked node itself if exceed maximum retry.
if (counter < counterLimit) {
counter++;
handler.postDelayed(this, DELAY_FIND_NODE_MILLISEC);
} else {
// Set focus on the clicked node.
clickedNode.performAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null);
// Close search UI.
hide();
}
}
}
},
DELAY_FIND_NODE_MILLISEC);
}
@Override
public void onClick(DialogInterface dialogInterface, int which) {
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
Fragment fragment;
final Bundle bundle = new Bundle();
switch (which) {
case 0:
ClipData clipAddress = ClipData.newPlainText(getActivity().getString(R.string.address), address);
clipboard.setPrimaryClip(clipAddress);
break;
case 1:
fragment = new TangleExplorerTabFragment();
bundle.putString(Constants.TANGLE_EXPLORER_SEARCH_ITEM, address);
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.showFragment(fragment);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
EventBus.getDefault().post(bundle);
}
}, 300);
break;
case 2:
if (!isAddressUsed) {
QRCode qrCode = new QRCode();
qrCode.setAddress(address);
bundle.putParcelable(Constants.QRCODE, qrCode);
fragment = new GenerateQRCodeFragment();
fragment.setArguments(bundle);
getActivity().getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.container, fragment, null)
.addToBackStack(null)
.commit();
} else {
Snackbar.make(getActivity().findViewById(R.id.drawer_layout), getString(R.string.messages_address_used), Snackbar.LENGTH_LONG).show();
}
break;
}
}
/**
* 淡出式停止,有bug,暂不使用
*
* @param handler
*/
public void fadeStop(Handler handler) {
mFadeOutRunnable = new FadeOutRunnable(handler, FADE_DURATION);
handler.postDelayed(mFadeOutRunnable, 1000);
}