Java Code Examples for android.os.Handler#post()

The following examples show how to use android.os.Handler#post() . 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: ActivityOptions.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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();
                    }
                });
            }
        };
    }
}
 
Example 2
Source File: WebViewAppTest.java    From unity-ads-android with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 3
Source File: Notifications.java    From Popeens-DSub with GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 4
Source File: NowPlayingFragment.java    From Popeens-DSub with GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 5
Source File: MidiDeviceMonitor.java    From android-midisuite with Apache License 2.0 6 votes vote down vote up
@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);
                }
            });
        }
    }
}
 
Example 6
Source File: OnDeleteDownloadFileListener.java    From file-downloader with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    });
}
 
Example 7
Source File: MainActivity.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example 8
Source File: DocViewBase.java    From Mupdf with Apache License 2.0 6 votes vote down vote up
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();
			}
		});
	}
}
 
Example 9
Source File: OnDeleteDownloadFilesListener.java    From file-downloader with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    });
}
 
Example 10
Source File: MyContentProvider1.java    From DroidPlugin with GNU Lesser General Public License v3.0 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 11
Source File: BluetoothOffClearGattServerStrategy.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
@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);
    });
}
 
Example 12
Source File: VisibleRegionDemoActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
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);
            }
        }
    });
}
 
Example 13
Source File: WaltTcpConnection.java    From walt with Apache License 2.0 5 votes vote down vote up
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();
                }
            });
        }
    });

}
 
Example 14
Source File: MainActivity.java    From android_gisapp with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 15
Source File: YouTubeExtractor.java    From YouTubeExtractor with Apache License 2.0 4 votes vote down vote up
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();
		}
	}
});
}
 
Example 16
Source File: ProfileListWidgetProvider.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
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;
                }
            });
        }
        */
    }
}
 
Example 17
Source File: FileOperation.java    From Camera-Roll-Android-App with Apache License 2.0 4 votes vote down vote up
public void runOnUiThread(Runnable r) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(r);
}
 
Example 18
Source File: ContactsContentObserver.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@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) {}
                }
            }
        }
    });
}
 
Example 19
Source File: NFCEventEndBroadcastReceiver.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
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);
            }
        }*/
    }
}
 
Example 20
Source File: MainActivity.java    From DeAutherDroid with Apache License 2.0 4 votes vote down vote up
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();
        }
    }