List of usage examples for android.os Handler post
public final boolean post(Runnable r)
From source file:com.dngames.mobilewebcam.PhotoSettings.java
public void DownloadImprintBitmap() { // get from URL Handler h = new Handler(mContext.getMainLooper()); h.post(new Runnable() { @Override/*from w w w.ja v a2s .c o m*/ public void run() { try { new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { try { URL url = new URL(mImprintPictureURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream is = connection.getInputStream(); return BitmapFactory.decodeStream(is); } catch (MalformedURLException e) { if (e.getMessage() != null) MobileWebCam.LogE("Imprint picture URL error: " + e.getMessage()); else MobileWebCam.LogE("Imprint picture URL invalid!"); e.printStackTrace(); } catch (IOException e) { if (e.getMessage() != null) MobileWebCam.LogE(e.getMessage()); e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap result) { if (result == null && !mNoToasts) Toast.makeText(mContext, "Imprint picture download failed!", Toast.LENGTH_SHORT) .show(); synchronized (PhotoSettings.gImprintBitmapLock) { PhotoSettings.gImprintBitmap = result; } } }.execute().get(); } catch (Exception e) { if (e.getMessage() != null) MobileWebCam.LogE(e.getMessage()); e.printStackTrace(); } } }); }
From source file:github.daneren2005.dsub.util.Util.java
public static void showPlayingNotification(final Context context, final DownloadServiceImpl downloadService, Handler handler, MusicDirectory.Entry song) { // Set the icon, scrolling text and timestamp final Notification notification = new Notification(R.drawable.stat_notify_playing, song.getTitle(), System.currentTimeMillis()); notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; boolean playing = downloadService.getPlayerState() == PlayerState.STARTED; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { RemoteViews expandedContentView = new RemoteViews(context.getPackageName(), R.layout.notification_expanded); setupViews(expandedContentView, context, song, playing); notification.bigContentView = expandedContentView; }/*from w ww . ja v a 2 s. c o m*/ RemoteViews smallContentView = new RemoteViews(context.getPackageName(), R.layout.notification); setupViews(smallContentView, context, song, playing); notification.contentView = smallContentView; Intent notificationIntent = new Intent(context, DownloadActivity.class); notification.contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); handler.post(new Runnable() { @Override public void run() { downloadService.startForeground(Constants.NOTIFICATION_ID_PLAYING, notification); } }); // Update widget DSubWidgetProvider.getInstance().notifyChange(context, downloadService, true); }
From source file:net.sourceforge.kalimbaradio.androidapp.activity.DownloadActivity.java
private void scheduleHideControls() { if (hideControlsFuture != null) { hideControlsFuture.cancel(false); }/*w w w . jav a2 s . co m*/ final Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { setControlsVisible(false); } }); } }; hideControlsFuture = executorService.schedule(runnable, 3000L, TimeUnit.MILLISECONDS); }
From source file:com.nextgis.mobile.activity.MainActivity.java
protected void stopRefresh(final MenuItem refreshItem) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) return;//from w ww . j a v a 2 s . c o m Handler handler = new Handler(Looper.getMainLooper()); final Runnable r = new Runnable() { @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void run() { if (refreshItem != null && refreshItem.getActionView() != null) { refreshItem.getActionView().clearAnimation(); refreshItem.setActionView(null); } } }; handler.post(r); }
From source file:org.catrobat.catroid.uitest.util.UiTestUtils.java
public static void longClickAndDrag(final Solo solo, final float xFrom, final float yFrom, final float xTo, final float yTo, final int steps) { final Activity activity = solo.getCurrentActivity(); Handler handler = new Handler(activity.getMainLooper()); handler.post(new Runnable() { public void run() { MotionEvent downEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, xFrom, yFrom, 0); activity.dispatchTouchEvent(downEvent); downEvent.recycle();/*from w w w .j av a 2 s . c o m*/ } }); solo.sleep(ViewConfiguration.getLongPressTimeout() + 200); handler.post(new Runnable() { public void run() { double offsetX = xTo - xFrom; offsetX /= steps; double offsetY = yTo - yFrom; offsetY /= steps; for (int i = 0; i <= steps; i++) { float x = xFrom + (float) (offsetX * i); float y = yFrom + (float) (offsetY * i); MotionEvent moveEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_MOVE, x, y, 0); activity.dispatchTouchEvent(moveEvent); solo.sleep(20); moveEvent.recycle(); } } }); solo.sleep(steps * 20 + 200); handler.post(new Runnable() { public void run() { MotionEvent upEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, xTo, yTo, 0); activity.dispatchTouchEvent(upEvent); upEvent.recycle(); Log.d(TAG, "longClickAndDrag finished: " + (int) yTo); } }); solo.sleep(1000); }
From source file:net.sourceforge.kalimbaradio.androidapp.activity.DownloadActivity.java
@Override protected void onResume() { super.onResume(); executorService = Executors.newSingleThreadScheduledExecutor(); final Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override/*from ww w . ja v a2 s . c o m*/ public void run() { handler.post(new Runnable() { @Override public void run() { update(); } }); } }; executorService.scheduleWithFixedDelay(runnable, 0L, 1000L, TimeUnit.MILLISECONDS); setControlsVisible(true); DownloadService downloadService = getDownloadService(); if (downloadService == null || downloadService.getCurrentPlaying() == null) { playlistFlipper.setDisplayedChild(1); } onDownloadListChanged(); onCurrentChanged(); onProgressChanged(); scrollToCurrent(); if (downloadService != null && downloadService.getKeepScreenOn()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } if (visualizerView != null) { visualizerView.setActive(downloadService != null && downloadService.getShowVisualization()); } boolean offline = Util.isOffline(this); //shareButton.setVisibility(offline ? View.GONE : View.VISIBLE); //starButton.setVisibility(offline ? View.GONE : View.VISIBLE); updateButtons(); }
From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java
/** * Sends the JSON RPC request through HTTP, and calls the callback with the raw response, * not parsed into the internal representation. * Useful for sync methods that don't want to incur the overhead of constructing the * internal objects./*from w ww .j a va 2s. co m*/ * * @param method Method object that represents the method too call * @param callback {@link ApiCallback} to post the response to. This will be the raw * {@link ObjectNode} received * @param handler {@link Handler} to invoke callbacks on * @param <T> Method return type */ public <T> void executeRaw(final ApiMethod<T> method, final ApiCallback<ObjectNode> callback, final Handler handler) { String jsonRequest = method.toJsonString(); try { HttpURLConnection connection = openHttpConnection(hostInfo); sendHttpRequest(connection, jsonRequest); // Read response and convert it final ObjectNode result = parseJsonResponse(readHttpResponse(connection)); if ((handler != null) && (callback != null)) { handler.post(new Runnable() { @Override public void run() { callback.onSucess(result); } }); } } catch (final ApiException e) { // Got an error, call error handler if ((handler != null) && (callback != null)) { handler.post(new Runnable() { @Override public void run() { callback.onError(e.getCode(), e.getMessage()); } }); } } }
From source file:com.example.sans.myapplication.AssignActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_assign); final SharedPreferences shares = getSharedPreferences("SHARES", 0); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);/* w ww .ja v a 2 s .c o m*/ //requestWindowFeature(Window.FEATURE_NO_TITLE); actionBarTitle = (TextView) toolbar.findViewById(R.id.action_bar_title); Intent i = getIntent(); Bundle bundle = i.getExtras(); try { j = new JSONObject(bundle.getString("data", "ERROR")); } catch (JSONException e) { Toast.makeText(AssignActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } new Thread(new Runnable() { @Override public void run() { for (int i = 30; i > 0; i--) { try { Thread.sleep(1000); final int finalI = i; runOnUiThread(new Runnable() { @Override public void run() { actionBarTitle.setText("" + finalI + ""); } }); } catch (InterruptedException e) { e.printStackTrace(); } } Handler mainHandler = new Handler(AssignActivity.this.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { final Client client = new Client(); RequestParams params = new RequestParams(); client.addHeader("Authorization", shares.getString("ACCESS_TOKEN", "ERROR")); client.post("OrderDistributor/rejectOrder", params, new JsonHttpResponseHandler()); } }; mainHandler.post(myRunnable); AssignActivity.this.finish(); } }).start(); setUpMapIfNeeded(); //Initializing NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view); header = navigationView.inflateHeaderView(R.layout.header); JSONObject driver_data = null; try { driver_data = new JSONObject(shares.getString("DRIVER_DATA", "ERROR")); } catch (JSONException e) { e.printStackTrace(); } TextView driver_name_header = (TextView) header.findViewById(R.id.username); TextView car_id_header = (TextView) header.findViewById(R.id.car_id); final ImageView pp_header = (ImageView) header.findViewById(R.id.profile_image); try { car_id_header.setText(driver_data.getString("license")); driver_name_header.setText(driver_data.getString("name")); Client client = new Client(); client.get(driver_data.getString("image"), new FileAsyncHttpResponseHandler(AssignActivity.this.getApplicationContext()) { @Override public void onFailure(int i, Header[] headers, Throwable throwable, File file) { } @Override public void onSuccess(int statusCode, Header[] headers, final File response) { AssignActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Bitmap image = BitmapFactory.decodeFile(response.getPath()); pp_header.setImageBitmap(image); } }); } }); } catch (JSONException e) { e.printStackTrace(); } header.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(AssignActivity.this, MenuItemActivity.class); i.putExtra("MENU_ITEM", 0); AssignActivity.this.startActivity(i); drawerLayout.closeDrawers(); } }); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { // This method will trigger on item Click of navigation menu @Override public boolean onNavigationItemSelected(MenuItem menuItem) { //Checking if the item is in checked state or not, if not make it in checked state nav = true; menuItem.setChecked(false); //Closing drawer on item click drawerLayout.closeDrawers(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); Fragment fragment; //Check to see which item was being clicked and perform appropriate action switch (menuItem.getItemId()) { case R.id.timetable: case R.id.service: case R.id.history: case R.id.mission: case R.id.points: case R.id.notice: Intent i = new Intent(AssignActivity.this, MenuItemActivity.class); i.putExtra("MENU_ITEM", menuItem.getItemId()); AssignActivity.this.startActivity(i); break; case R.id.login: Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show(); SharedPreferences.Editor editor = shares.edit(); final Client client = new Client(); RequestParams params = new RequestParams(); params.put("id", shares.getInt("ID", 0)); params.put("status", 999); client.post("driver/setStatus", params, new JsonHttpResponseHandler()); editor.putBoolean("ONLINE", false); editor.putBoolean("LOGIN", false); editor.commit(); Intent intent = getApplicationContext().getPackageManager() .getLaunchIntentForPackage(getApplicationContext().getPackageName()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); break; default: Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show(); break; } return false; } }); reject = (Button) findViewById(R.id.reject); reject.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Client client = new Client(); RequestParams params = new RequestParams(); client.addHeader("Authorization", shares.getString("ACCESS_TOKEN", "ERROR")); client.post("OrderDistributor/rejectOrder", params, new JsonHttpResponseHandler()); AssignActivity.this.finish(); } }); accept = (Button) findViewById(R.id.accept); accept.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Client client = new Client(); final RequestParams params = new RequestParams(); try { params.put("orderId", j.getJSONObject("order_data").getDouble("id")); client.addHeader("Authorization", shares.getString("ACCESS_TOKEN", "ERROR")); client.post("OrderDistributor/takeOrder", params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { } @Override public void onFailure(int statusCode, Header[] headers, Throwable error, JSONObject response) { Log.i("Status Code", "" + statusCode); } }); AssignActivity.this.finish(); } catch (JSONException e) { e.printStackTrace(); } } }); // Initializing Drawer Layout and ActionBarToggle drawerLayout = (DrawerLayout) findViewById(R.id.drawer); ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) { @Override public void onDrawerClosed(View drawerView) { // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank super.onDrawerClosed(drawerView); drawerLayout.setSelected(false); } @Override public void onDrawerOpened(View drawerView) { // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank super.onDrawerOpened(drawerView); } }; //Setting the actionbarToggle to drawer layout drawerLayout.setDrawerListener(actionBarDrawerToggle); //calling sync state is necessay or else your hamburger icon wont show up actionBarDrawerToggle.syncState(); }
From source file:com.flowzr.export.flowzr.FlowzrSyncEngine.java
public static String create(Context p_context, DatabaseAdapter p_dba, DefaultHttpClient p_http) { startTimestamp = System.currentTimeMillis(); if (isRunning == true) { isCanceled = true;// w w w. j a v a 2 s . co m isRunning = false; } isRunning = true; boolean recordSyncTime = true; dba = p_dba; db = dba.db(); em = dba.em(); http_client = p_http; context = p_context; last_sync_ts = MyPreferences.getFlowzrLastSync(context); FLOWZR_BASE_URL = "https://" + MyPreferences.getSyncApiUrl(context); FLOWZR_API_URL = FLOWZR_BASE_URL + "/financisto3/"; nsString = MyPreferences.getFlowzrAccount(context).replace("@", "_"); //urlsafe Log.i(TAG, "init sync engine, last sync was " + new Date(last_sync_ts).toLocaleString()); //if (true) { if (!checkSubscriptionFromWeb()) { Intent notificationIntent = new Intent(context, FlowzrSyncActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.icon) .setTicker(context.getString(R.string.flowzr_subscription_required)) .setContentTitle(context.getString(R.string.flowzr_sync_error)) .setContentText(context.getString(R.string.flowzr_subscription_required, MyPreferences.getFlowzrAccount(context))) .setContentIntent(pendingIntent).setAutoCancel(true).build(); notificationManager.notify(0, notification); Log.w("flowzr", "subscription rejected from web"); isCanceled = true; MyPreferences.unsetAutoSync(context); return null; } else { mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Sets an ID for the notification, so it can be updated mNotifyBuilder = new NotificationCompat.Builder(context).setAutoCancel(true) .setContentTitle(context.getString(R.string.flowzr_sync)) .setContentText(context.getString(R.string.flowzr_sync_inprogress)) .setSmallIcon(R.drawable.icon); } if (!isCanceled) { notifyUser("fix created entities", 5); fixCreatedEntities(); } /** * pull delete */ if (!isCanceled) { notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 10); try { pullDelete(last_sync_ts); } catch (Exception e) { sendBackTrace(e); recordSyncTime = false; } } /** * push delete */ if (!isCanceled) { notifyUser(context.getString(R.string.flowzr_sync_sending) + " ...", 15); try { pushDelete(); } catch (Exception e) { sendBackTrace(e); recordSyncTime = false; } } /** * pull update */ if (!isCanceled && last_sync_ts == 0) { notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 20); try { pullUpdate(); } catch (IOException e) { sendBackTrace(e); recordSyncTime = false; } catch (JSONException e) { sendBackTrace(e); recordSyncTime = false; } catch (Exception e) { sendBackTrace(e); recordSyncTime = false; } } /** * push update */ if (!isCanceled) { notifyUser(context.getString(R.string.flowzr_sync_sending) + " ...", 35); try { pushUpdate(); } catch (ClientProtocolException e) { e.printStackTrace(); sendBackTrace(e); recordSyncTime = false; } catch (IOException e) { e.printStackTrace(); sendBackTrace(e); recordSyncTime = false; } catch (JSONException e) { e.printStackTrace(); sendBackTrace(e); recordSyncTime = false; } catch (Exception e) { e.printStackTrace(); recordSyncTime = false; } } /** * pull update */ if (!isCanceled && last_sync_ts > 0) { notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 20); try { pullUpdate(); } catch (IOException e) { sendBackTrace(e); recordSyncTime = false; } catch (JSONException e) { sendBackTrace(e); recordSyncTime = false; } catch (Exception e) { sendBackTrace(e); recordSyncTime = false; } } notifyUser(context.getString(R.string.integrity_fix), 80); new IntegrityFix(dba).fix(); /** * send account balances boundaries */ if (!isCanceled) { //if (true) { //will generate a Cloud Messaging request if prev. aborted notifyUser(context.getString(R.string.flowzr_sync_sending) + "...", 85); //nm.notify(NOTIFICATION_ID, mNotifyBuilder.build()); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("action", "balancesRecalc")); nameValuePairs.add(new BasicNameValuePair("last_sync_ts", String.valueOf(last_sync_ts))); String serialNumber = Build.SERIAL != Build.UNKNOWN ? Build.SERIAL : Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); nameValuePairs.add(new BasicNameValuePair("serialNumber", serialNumber)); List<Account> accountsList = em.getAllAccountsList(); for (Account account : accountsList) { nameValuePairs.add(new BasicNameValuePair(account.remoteKey, String.valueOf(account.totalAmount))); Log.i("flowzr", account.remoteKey + " " + String.valueOf(account.totalAmount)); } try { httpPush(nameValuePairs, "balances"); } catch (Exception e) { sendBackTrace(e); } } notifyUser("Widgets ...", 90); AccountWidget.updateWidgets(context); Handler refresh = new Handler(Looper.getMainLooper()); refresh.post(new Runnable() { public void run() { if (currentActivity != null) { //currentActivity.refreshCurrentTab(); } } }); if (!isCanceled && MyPreferences.doGoogleDriveUpload(context)) { notifyUser(context.getString(R.string.flowzr_sync_sending) + " Google Drive", 95); pushAllBlobs(); } else { Log.i("flowzr", "picture upload desactivated in prefs"); } notifyUser(context.getString(R.string.flowzr_sync_success), 100); if (isCanceled == false) { if (recordSyncTime == true) { last_sync_ts = System.currentTimeMillis(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putLong("PROPERTY_LAST_SYNC_TIMESTAMP", last_sync_ts); editor.commit(); } } // mNotificationManager.cancel(NOTIFICATION_ID); isRunning = false; isCanceled = false; if (context instanceof FlowzrSyncActivity) { ((FlowzrSyncActivity) context).setIsFinished(); } return FLOWZR_BASE_URL; }
From source file:com.sentaroh.android.TextFileBrowser.FileViewerFragment.java
private void startScroll(final ThreadCtrl tc, final int move) { final Handler hndl = new Handler(); mScrollActive = true;//from www .ja v a2 s. com mThScroll = new Thread() { @Override public void run() { while (tc.isEnabled()) { hndl.post(new Runnable() { @Override public void run() { if (move > 0) mTextListAdapter.incrementHorizontalPosition(move); else mTextListAdapter.decrementHorizontalPosition(move * -1); mTextListAdapter.notifyDataSetChanged(); } }); waitSpecifiedTime(200); } mScrollActive = false; mTcScroll.setEnabled(); } }; mThScroll.start(); }