下面列出了android.os.Handler#post ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void setOnAnimationFinishedListener(final Handler handler,
final OnAnimationFinishedListener listener) {
if (listener != null) {
mAnimationFinishedListener = new IRemoteCallback.Stub() {
@Override
public void sendResult(Bundle data) throws RemoteException {
handler.post(new Runnable() {
@Override
public void run() {
listener.onAnimationFinished();
}
});
}
};
}
}
@Test
public void testInvokeMethodShouldSucceed () throws Exception {
WebViewApp.setCurrentApp(null);
final ConditionVariable cv = new ConditionVariable();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
WebViewApp.setCurrentApp(new WebViewApp());
WebViewApp.getCurrentApp().setWebView(new MockWebView(InstrumentationRegistry.getContext()));
WebViewApp.getCurrentApp().setWebAppLoaded(true);
WebViewApp.getCurrentApp().setWebAppInitialized(true);
cv.open();
}
});
boolean cvsuccess = cv.block(10000);
assertTrue("ConditionVariable was not opened successfully", cvsuccess);
Method m = getClass().getMethod("testNativeCallbackMethod");
boolean success = WebViewApp.getCurrentApp().invokeMethod("TestClass", "testMethod", m);
assertTrue("invokeMethod -method should've returned true", success);
assertTrue("WebView invokeJavascript should've succeeded but didn't", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_INVOKED);
assertNotNull("The invoked JavaScript string should not be null.", ((MockWebView) WebViewApp.getCurrentApp().getWebView()).JS_CALL);
}
@Override
public void onDeviceAdded(final MidiDeviceInfo device) {
// Call all of the locally registered callbacks.
for(Map.Entry<DeviceCallback, Handler> item : mCallbacks.entrySet()) {
final DeviceCallback callback = item.getKey();
Handler handler = item.getValue();
if(handler == null) {
callback.onDeviceAdded(device);
} else {
handler.post(new Runnable() {
@Override
public void run() {
callback.onDeviceAdded(device);
}
});
}
}
}
/**
* delete failed
*
* @param downloadFileInfo download file needed to delete,may be null
* @param failReason fail reason
*/
public static void onDeleteDownloadFileFailed(final DownloadFileInfo downloadFileInfo, final
DeleteDownloadFileFailReason failReason, final OnDeleteDownloadFileListener onDeleteDownloadFileListener) {
if (onDeleteDownloadFileListener == null) {
return;
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (onDeleteDownloadFileListener == null) {
return;
}
onDeleteDownloadFileListener.onDeleteDownloadFileFailed(downloadFileInfo, failReason);
}
});
}
public void getMainHtml(){
Handler handler = new Handler();
Thread t = new Thread(() -> {
downloader = KcaUtils.getH5InfoDownloader(getApplicationContext());
String locale = getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE);
String localCode = getLocaleCode(locale);
final Call<String> rv_data = downloader.getH5MainHtml(localCode);
String response = getResultFromCall(rv_data);
try {
if (response != null) {
handler.post(() -> {
Spanned fromHtml = HtmlCompat.fromHtml(getApplicationContext(), response, 0);
textDescription.setMovementMethod(LinkMovementMethod.getInstance());
textDescription.setText(fromHtml);
});
}
} catch (Exception e) {
dbHelper.recordErrorLog(ERROR_TYPE_MAIN, "version_check", "", "", getStringFromException(e));
}
});
t.start();
}
public void handleStartPage()
{
// if we've been given a start page, go there.
final int start = getStartPage();
if (start > 0)
{
setStartPage(0); // but just once
// post all of this so that we get an additional layout request
final Handler handler = new Handler();
handler.post(new Runnable()
{
@Override
public void run()
{
DocPageView cv = (DocPageView) getOrCreateChild(start - 1);
Rect r = cv.getChildRect();
scrollBy(0, r.top);
requestLayout();
}
});
}
}
/**
* delete multi completed
*
* @param downloadFilesNeedDelete download files needed to delete
* @param downloadFilesDeleted download files deleted
*/
public static void onDeleteDownloadFilesCompleted(final List<DownloadFileInfo> downloadFilesNeedDelete, final
List<DownloadFileInfo> downloadFilesDeleted, final OnDeleteDownloadFilesListener
onDeleteDownloadFilesListener) {
if (onDeleteDownloadFilesListener == null) {
return;
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (onDeleteDownloadFilesListener == null) {
return;
}
onDeleteDownloadFilesListener.onDeleteDownloadFilesCompleted(downloadFilesNeedDelete,
downloadFilesDeleted);
}
});
}
private void scheduleHideControls() {
if (hideControlsFuture != null) {
hideControlsFuture.cancel(false);
}
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
//TODO, make a setting to turn this on & off
// setControlsVisible(false);
}
});
}
};
hideControlsFuture = executorService.schedule(runnable, 3000L, TimeUnit.MILLISECONDS);
}
public static void hidePlayingNotification(final Context context, final DownloadService downloadService, Handler handler) {
playShowing = false;
// Remove notification and remove the service from the foreground
handler.post(new Runnable() {
@Override
public void run() {
stopForeground(downloadService, true);
if(persistentPlayingShowing) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID_PLAYING);
persistentPlayingShowing = false;
}
}
});
// Get downloadNotification in foreground if playing
if(downloadShowing) {
showDownloadingNotification(context, downloadService, handler, downloadService.getCurrentDownloading(), downloadService.getBackgroundDownloads().size());
}
// Update widget
DSubWidgetProvider.notifyInstances(context, downloadService, false);
}
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);
}
protected void stopRefresh(final MenuItem refreshItem) {
Handler handler = new Handler(Looper.getMainLooper());
final Runnable r = new Runnable() {
public void run() {
if (refreshItem != null && refreshItem.getActionView() != null) {
refreshItem.getActionView().clearAnimation();
refreshItem.setActionView(null);
}
}
};
handler.post(r);
}
public void connect() {
connectionState = Utils.ListenerState.STARTING;
networkThread = new HandlerThread("NetworkThread");
networkThread.start();
networkHandler = new Handler(networkThread.getLooper());
logger.log("Started network thread for TCP bridge");
networkHandler.post(new Runnable() {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVER_PORT);
socket.setSoTimeout(TCP_READ_TIMEOUT_MS);
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
logger.log("TCP connection established");
connectionState = Utils.ListenerState.RUNNING;
} catch (Exception e) {
e.printStackTrace();
logger.log("Can't connect to TCP bridge: " + e.getMessage());
connectionState = Utils.ListenerState.STOPPED;
return;
}
// Run the onConnect callback, but on main thread.
mainHandler.post(new Runnable() {
@Override
public void run() {
WaltTcpConnection.this.onConnect();
}
});
}
});
}
public void animatePadding(
final int toLeft, final int toTop, final int toRight, final int toBottom) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 1000;
final Interpolator interpolator = new OvershootInterpolator();
final int startLeft = currentLeft;
final int startTop = currentTop;
final int startRight = currentRight;
final int startBottom = currentBottom;
currentLeft = toLeft;
currentTop = toTop;
currentRight = toRight;
currentBottom = toBottom;
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
int left = (int) (startLeft + ((toLeft - startLeft) * t));
int top = (int) (startTop + ((toTop - startTop) * t));
int right = (int) (startRight + ((toRight - startRight) * t));
int bottom = (int) (startBottom + ((toBottom - startBottom) * t));
mMap.setPadding(left, top, right, bottom);
if (elapsed < duration) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
@Override
public void applyStrategy() {
// we want to clear the services on the server, however we must make sure that we do not
// crash in a stack NPE if the bluetooth service has crashed or is shut down, and we want
// to make sure that this does not occur on the main thread since this probably transits
// the JNI and could lead to a ANR
Handler strategyHandler = new Handler(FitbitGatt.getInstance().getFitbitGattAsyncOperationThread().getLooper());
strategyHandler.post(() -> {
GattServerConnection serverConn = FitbitGatt.getInstance().getServer();
if(serverConn == null) {
Timber.i("Server connection was null when trying to execute strategy");
return;
}
// make it disconnected so that no one can use it
serverConn.setState(GattState.DISCONNECTED);
BluetoothGattServer gattServer = serverConn.getServer();
if(gattServer == null) {
Timber.i("Android BluetoothGattServer instance was null when trying to execute strategy");
return;
}
try {
/* this may not execute instantly, so considering some sort of delay between
* clear, close and release ... in the downside of a delay is that the BT service
* may go away while we are waiting, so opting for now to just go for it and hope
* that the queue system does the right thing.
*/
gattServer.clearServices();
} catch (NullPointerException e) {
Timber.w(e, "There was an internal stack NPE, the Android BluetoothService probably crashed or already shut down");
}
serverConn.setState(GattState.IDLE);
});
}
public void startExtracting(final YouTubeExtractorListener listener) {
String elField = mElFields.get(0);
mElFields.remove(0);
if (elField.length() > 0) elField = "&el=" + elField;
final String language = Locale.getDefault().getLanguage();
final String link = String.format("https://www.youtube.com/get_video_info?video_id=%s%s&ps=default&eurl=&gl=US&hl=%s", mVideoIdentifier, elField, language);
final HandlerThread youtubeExtractorThread = new HandlerThread("YouTubeExtractorThread", THREAD_PRIORITY_BACKGROUND);
youtubeExtractorThread.start();
final Handler youtubeExtractorHandler = new Handler(youtubeExtractorThread.getLooper());
final Handler listenerHandler = new Handler(Looper.getMainLooper());
youtubeExtractorHandler.post(new Runnable() {
@Override public void run() {
try {
mConnection = (HttpsURLConnection) new URL(link).openConnection();
mConnection.setRequestProperty("Accept-Language", language);
BufferedReader reader = new BufferedReader(new InputStreamReader(mConnection.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null && !mCancelled) builder.append(line);
reader.close();
if (!mCancelled) {
final YouTubeExtractorResult result = getYouTubeResult(builder.toString());
listenerHandler.post(new Runnable() {
@Override public void run() {
if (!mCancelled && listener != null) {
listener.onSuccess(result);
}
}
});
}
} catch (final Exception e) {
listenerHandler.post(new Runnable() {
@Override public void run() {
if (!mCancelled && listener != null) {
listener.onFailure(new Error(e));
}
}
});
} finally {
if (mConnection != null) {
mConnection.disconnect();
}
youtubeExtractorThread.quit();
}
}
});
}
private void doWork(/*boolean useHandler,*/ Context context) {
//PPApplication.logE("[HANDLER] NFCEventEndBroadcastReceiver.doWork", "useHandler="+useHandler);
final Context appContext = context.getApplicationContext();
if (!PPApplication.getApplicationStarted(true))
// application is not started
return;
if (Event.getGlobalEventsRunning()) {
//if (useHandler) {
PPApplication.startHandlerThread(/*"NFCEventEndBroadcastReceiver.doWork"*/);
final Handler handler = new Handler(PPApplication.handlerThread.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":NFCEventEndBroadcastReceiver_doWork");
wakeLock.acquire(10 * 60 * 1000);
}
//PPApplication.logE("****** EventsHandler.handleEvents", "START run - from=NFCEventEndBroadcastReceiver.doWork");
EventsHandler eventsHandler = new EventsHandler(appContext);
eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_NFC_EVENT_END);
//PPApplication.logE("****** EventsHandler.handleEvents", "END run - from=NFCEventEndBroadcastReceiver.doWork");
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
}
});
/*}
else {
if (Event.getGlobalEventsRunning(appContext)) {
PPApplication.logE("NFCEventEndBroadcastReceiver.doWork", "handle events");
EventsHandler eventsHandler = new EventsHandler(appContext);
eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_NFC_EVENT_END);
}
}*/
}
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
//CallsCounter.logCounter(context, "ContactsContentObserver.onChange", "ContactContentObserver_onChange");
PPApplication.startHandlerThread(/*"ContactsContentObserver.onChange"*/);
final Handler handler = new Handler(PPApplication.handlerThread.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (context == null)
return;
Context appContext = context.getApplicationContext();
if (appContext == null)
return;
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":PhoneProfilesService_doForFirstStart");
wakeLock.acquire(10 * 60 * 1000);
}
// must be first
PhoneProfilesService.createContactsCache(context.getApplicationContext(), true);
//must be seconds, this ads groups int contacts
PhoneProfilesService.createContactGroupsCache(context.getApplicationContext(), true);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {}
}
}
}
});
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
//super.onUpdate(context, appWidgetManager, appWidgetIds);
if (appWidgetIds.length > 0) {
final Context _context = context;
final AppWidgetManager _appWidgetManager = appWidgetManager;
final int[] _appWidgetIds = appWidgetIds;
PPApplication.startHandlerThreadListWidget();
final Handler handler = new Handler(PPApplication.handlerThreadListWidget.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
//createProfilesDataWrapper(_context);
for (int appWidgetId : _appWidgetIds) {
doOnUpdate(_context, _appWidgetManager, appWidgetId, true);
}
//if (dataWrapper != null)
// dataWrapper.invalidateDataWrapper();
//dataWrapper = null;
}
});
/*
if (PPApplication.widgetHandler != null) {
PPApplication.widgetHandler.post(new Runnable() {
public void run() {
createProfilesDataWrapper(context);
for (int appWidgetId : appWidgetIds) {
doOnUpdate(context, appWidgetManager, appWidgetId);
}
if (dataWrapper != null)
dataWrapper.invalidateDataWrapper();
dataWrapper = null;
}
});
}
*/
}
}
public void runOnUiThread(Runnable r) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(r);
}
private void showScanResults() {
View scanView = getLayoutInflater().inflate(R.layout.view_list, null);
listView = scanView.findViewById(R.id.list);
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (manager != null) {
manager.startScan();
}
Handler handlerX = new Handler();
handlerX.post(new Runnable() {
@Override
public void run() {
WifiUtils.withContext(getApplicationContext()).scanWifi(results -> {
List<String> arrayWIFIList = new ArrayList<>();
ScanResult result;
for (int i = 0; i < results.size(); i++) {
result = results.get(i);
Log.v(TAG, result.toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
arrayWIFIList.add(i, result.SSID + "[" + (double) result.frequency / 1000 + "GHz" + "/" + result.level + "dBm" + "]"
+ result.capabilities + getChannelWidth(result.channelWidth));
} else {
arrayWIFIList.add(i, result.SSID + "[" + (double) result.frequency / 1000 + "GHz" + "/" + result.level + "dBm" + "]"
+ result.capabilities);
}
}
String[] stringArray = arrayWIFIList.toArray(new String[0]);
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(MainActivity.this, R.layout.list_text, R.id.textList, stringArray);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}).start();
handlerX.postDelayed(this, TimeUnit.SECONDS.toMillis(10));
}
});
if (Prefs.getInstance(getBaseContext()).isWIFIRand()) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (listView.getChildCount() > 0) {
for (int i = 0; i < listView.getChildCount(); i++) {
SecureRandom random = new SecureRandom(); /* Just some beautifying */
int color = Color.argb(255, random.nextInt(200), random.nextInt(200), random.nextInt(255));
((TextView) listView.getChildAt(i)).setTextColor(color);
}
}
handler.postDelayed(this, 250);
}
}, 100);
}
if (!MainActivity.this.isFinishing()) {
new AlertDialog.Builder(MainActivity.this)
.setView(scanView)
.setTitle("WiFi Scan-results (Local)")
.setCancelable(false)
.setOnDismissListener(dialog -> {
})
.setNeutralButton("Help", (dialog, which) -> new AlertDialog.Builder(MainActivity.this)
.setMessage(R.string.help_scan)
.setCancelable(false)
.setPositiveButton("Okay", null)
.show())
.setPositiveButton("Close / Stop Scan", null).show();
}
}