Example usage for android.os Handler Handler

List of usage examples for android.os Handler Handler

Introduction

In this page you can find the example usage for android.os Handler Handler.

Prototype

public Handler() 

Source Link

Document

Default constructor associates this handler with the Looper for the current thread.

Usage

From source file:com.QuarkLabs.BTCeClient.services.CheckTickersService.java

@Override
protected void onHandleIntent(Intent intent) {

    SharedPreferences sh = PreferenceManager.getDefaultSharedPreferences(this);
    Set<String> x = sh.getStringSet("PairsToDisplay", new HashSet<String>());
    if (x.size() == 0) {
        return;//from w w  w.  jav a 2s  . c  o m
    }
    String[] pairs = x.toArray(new String[x.size()]);
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    String url = BASE_URL;
    for (String xx : pairs) {
        url += xx.replace("/", "_").toLowerCase(Locale.US) + "-";
    }
    SimpleRequest reqSim = new SimpleRequest();

    if (networkInfo != null && networkInfo.isConnected()) {
        JSONObject data = null;
        try {
            data = reqSim.makeRequest(url);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (data != null && data.optInt("success", 1) != 0) {

            ArrayList<Ticker> tickers = new ArrayList<>();
            for (@SuppressWarnings("unchecked")
            Iterator<String> iterator = data.keys(); iterator.hasNext();) {
                String key = iterator.next();
                JSONObject pairData = data.optJSONObject(key);
                Ticker ticker = new Ticker(key);
                ticker.setUpdated(pairData.optLong("updated"));
                ticker.setAvg(pairData.optDouble("avg"));
                ticker.setBuy(pairData.optDouble("buy"));
                ticker.setSell(pairData.optDouble("sell"));
                ticker.setHigh(pairData.optDouble("high"));
                ticker.setLast(pairData.optDouble("last"));
                ticker.setLow(pairData.optDouble("low"));
                ticker.setVol(pairData.optDouble("vol"));
                ticker.setVolCur(pairData.optDouble("vol_cur"));
                tickers.add(ticker);
            }

            String message = checkNotifiers(tickers, TickersStorage.loadLatestData());

            if (message.length() != 0) {
                NotificationManager notificationManager = (NotificationManager) getSystemService(
                        NOTIFICATION_SERVICE);
                NotificationCompat.Builder nb = new NotificationCompat.Builder(this)
                        .setContentTitle(getResources().getString(R.string.app_name))
                        .setSmallIcon(R.drawable.ic_stat_bitcoin_sign)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setContentText(message.substring(0, message.length() - 2));
                notificationManager.notify(ConstantHolder.ALARM_NOTIF_ID, nb.build());
            }

            Map<String, Ticker> newData = new HashMap<>();
            for (Ticker ticker : tickers) {
                newData.put(ticker.getPair(), ticker);
            }
            TickersStorage.saveData(newData);
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("UpdateTickers"));
        }
    } else {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                //Toast.makeText(CheckTickersService.this, "Unable to fetch data", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

From source file:fr.bmartel.android.notti.service.bluetooth.BluetoothCustomManager.java

@SuppressLint("NewApi")
public void init(Context context) {

    // Initializes Bluetooth adapter.
    final BluetoothManager bluetoothManager = (BluetoothManager) context
            .getSystemService(Context.BLUETOOTH_SERVICE);

    mBluetoothAdapter = bluetoothManager.getAdapter();

    //init message handler
    mHandler = null;/*from  w ww  . jav  a2  s  .co m*/
    mHandler = new Handler();

    scanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(BluetoothDevice device, int rssi, final byte[] scanRecord) {

            if (device.getAddress() != null && device.getName() != null
                    && !scanningList.containsKey(device.getAddress())) {

                scanningList.put(device.getAddress(), device);

                try {
                    JSONObject object = new JSONObject();
                    object.put("address", device.getAddress());
                    object.put("deviceName", device.getName());

                    ArrayList<String> deviceInfo = new ArrayList<>();
                    deviceInfo.add(object.toString());

                    broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCOVERED, deviceInfo);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };
}

From source file:com.nadmm.airports.DownloadActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mDbManager = DatabaseManager.instance(this);
    mDownloadTask = null;/*from w ww.  java  2  s  . com*/
    mHandler = new Handler();

    setContentView(createContentView(R.layout.download_list_view));

    // Add the footer view
    View footer = inflate(R.layout.download_footer);
    mListView = (ListView) findViewById(android.R.id.list);
    mListView.addFooterView(footer);
    mListView.setFooterDividersEnabled(true);

    Button btnDownload = (Button) findViewById(R.id.btnDownload);
    btnDownload.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            checkNetworkAndDownload();
        }
    });

    Button btnDelete = (Button) findViewById(R.id.btnDelete);
    btnDelete.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            checkDelete();
        }
    });

    Intent intent = getIntent();
    if (intent.hasExtra("MSG")) {
        String msg = intent.getStringExtra("MSG");
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    checkData(false);
}

From source file:org.openremote.android.console.net.ORConnection.java

protected void initHandler(final Context context) {
    handler = new Handler() {
        @Override//from w  w  w  . j  a va 2s.c  o m
        public void handleMessage(Message msg) {
            int message = msg.what;
            if (message == ERROR) {
                connectionDidFailWithException(context,
                        new ORConnectionException("Httpclient execute httprequest fail."));
            } else {
                dealWithResponse();
            }
        }
    };
}

From source file:com.echopf.ECHOInstallation.java

/**
 * Does Get registration id from the GCM server in a background thread.
 * //  ww  w. j  ava  2  s.c om
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the fetching in a background thread. 
 *              (a synchronous communication)
 * @param callback invoked after the getting is completed
 * @throws ECHOException 
 */
protected void doGetRegistrationId(final boolean sync, final InstallationCallback callback)
        throws ECHOException {
    // if(!checkPlayServices(ECHO.context)) return;

    // Get senderId from AndroidManifest.xml
    String senderId = null;
    try {
        ApplicationInfo appInfo = ECHO.context.getPackageManager()
                .getApplicationInfo(ECHO.context.getPackageName(), PackageManager.GET_META_DATA);
        senderId = appInfo.metaData.getString(GCM_SENDER_ID_KEY);
        senderId = (senderId.startsWith("id:")) ? senderId.substring(3) : null;
    } catch (NameNotFoundException ignored) {
        // skip
    }
    if (senderId == null)
        throw new RuntimeException("`" + GCM_SENDER_ID_KEY + "` is not specified in `AndroidManifest.xml`.");

    // Get ready a background thread
    final Handler handler = new Handler();
    final String fSenderId = senderId;

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Object> communictor = new Callable<Object>() {

        @Override
        public Object call() throws ECHOException {
            ECHOException exception = null;

            // InstanceID instanceID = InstanceID.getInstance(ECHO.context);
            String token = null;

            // Get updated InstanceID token.
            token = FirebaseInstanceId.getInstance().getToken();
            // Log.d(TAG, "Refreshed token: " + refreshedToken);
            // TODO: Implement this method to send any registration to your app's servers.

            // token = instanceID.getToken(fSenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
            synchronized (lock) {
                deviceToken = token;
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                final ECHOException fException = exception;
                final String fToken = token;

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ECHOInstallation.this.deviceToken = fToken;
                        callback.done(fException);
                    }
                });

            } else {

                if (exception != null)
                    throw exception;

            }

            return null;
        }
    };

    Future<Object> future = executor.submit(communictor);

    if (sync) {
        try {
            future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }
}

From source file:com.ubikod.urbantag.ContentViewerActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle extras = getIntent().getExtras();

    /* If we are coming from Notification delete notification */
    if (extras.getInt(NotificationHelper.FROM_NOTIFICATION, -1) == NotificationHelper.NEW_CONTENT_NOTIF) {
        NotificationHelper notificationHelper = new NotificationHelper(this);
        notificationHelper.closeContentNotif();
    } else if (extras.getInt(NotificationHelper.FROM_NOTIFICATION, -1) == NotificationHelper.NEW_PLACE_NOTIF) {
        NotificationHelper notificationHelper = new NotificationHelper(this);
        notificationHelper.closePlaceNotif();
    }//from  w  w  w.  j  a  va2  s. co  m

    /* Fetch content info */
    ContentManager contentManager = new ContentManager(new DatabaseHelper(this, null));
    Log.i(UrbanTag.TAG, "View content : " + extras.getInt(CONTENT_ID));
    this.content = contentManager.get(extras.getInt(CONTENT_ID));
    if (this.content == null) {
        Toast.makeText(this, R.string.error_occured, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    setTitle(content.getName());
    com.actionbarsherlock.app.ActionBar actionBar = this.getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.content_viewer);

    /* Find webview and create url for content */
    final WebView webView = (WebView) findViewById(R.id.webview);
    final String URL = UrbanTag.API_URL + ACTION_GET_CONTENT.replaceAll("%", "" + this.content.getId());

    /* Display progress animation */
    final ProgressDialog progress = ProgressDialog.show(this, "",
            this.getResources().getString(R.string.loading_content), false, true,
            new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    timeOutHandler.interrupt();
                    webView.stopLoading();
                    ContentViewerActivity.this.finish();
                }

            });

    /* Go fetch content */
    contentFetcher = new Thread(new Runnable() {

        DefaultHttpClient httpClient;

        @Override
        public void run() {
            Looper.prepare();
            Log.i(UrbanTag.TAG, "Fetching content...");
            httpClient = new DefaultHttpClient();
            try {
                String responseBody = httpClient.execute(new HttpGet(URL), new BasicResponseHandler());
                webView.loadDataWithBaseURL("fake://url/for/encoding/hack...", responseBody, mimeType, encoding,
                        "");
                timeOutHandler.interrupt();
                if (progress.isShowing())
                    progress.dismiss();
            } catch (ClientProtocolException cpe) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                timeOutHandler.interrupt();
                progress.cancel();
            } catch (IOException ioe) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                timeOutHandler.interrupt();
                progress.cancel();
            }

            Looper.loop();
        }

    });
    contentFetcher.start();

    /* TimeOut Handler */
    timeOutHandler = new Thread(new Runnable() {
        private int INCREMENT = 1000;

        @Override
        public void run() {
            Looper.prepare();
            try {
                for (int time = 0; time < TIMEOUT; time += INCREMENT) {
                    Thread.sleep(INCREMENT);
                }

                Log.w(UrbanTag.TAG, "TimeOut !");
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });

                contentFetcher.interrupt();
                progress.cancel();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Looper.loop();

        }

    });
    timeOutHandler.start();

}

From source file:fr.shywim.antoinedaniel.utils.Utils.java

/**
 * Second part of the click animation.//from   w ww. jav a  2 s.  c  o  m
 *
 * @param v View who will have the effect.
 * @param isRoot Whether the passed view is the ViewGroup parent.
 */
public static void clickAnimUp(View v, boolean isRoot) {
    RelativeLayout root;
    if (isRoot)
        root = (RelativeLayout) v;
    else
        root = (RelativeLayout) v.getParent();
    final View rectView = root.findViewById(R.id.rect_view_id);
    if (rectView != null) {
        AlphaAnimation rectAnim = new AlphaAnimation(0.4f, 0f);
        rectAnim.setFillAfter(true);
        rectAnim.setInterpolator(new DecelerateInterpolator());
        rectAnim.setDuration(150);
        rectAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        ViewGroup parent = (ViewGroup) rectView.getParent();
                        rectView.setVisibility(View.GONE);
                        if (parent != null)
                            parent.removeView(rectView);
                    }
                });
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        rectView.clearAnimation();
        rectView.startAnimation(rectAnim);
    }
}

From source file:com.wahyuadityanugraha.mvpexample.app.finditems.FeedActivity.java

@Override
public void onRefresh() {
    new Handler().postDelayed(new Runnable() {
        @Override/*from   w  w w.  ja  v a 2  s.c  o m*/
        public void run() {
            mJsonObjectRequest = new JsonObjectRequest(API_URL, null, mObjectListener, errorListener);
            swipeContainer.setRefreshing(false);
        }
    }, 5000);
}

From source file:com.philips.castdemo.videobrowser.VideoBrowser.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    boolean result = VideoCastManager.checkGooglePlayServices(this);
    setContentView(R.layout.activity_video_browser);
    ActionBar actionBar = getSupportActionBar();
    mCastManager = CastApplication.getCastManager(this);

    // -- Adding MiniController
    mMini = (MiniController) findViewById(R.id.miniController1);
    mCastManager.addMiniController(mMini);

    mCastConsumer = new VideoCastConsumerImpl() {

        @Override//from w  ww . j  a  va  2s. c  o m
        public void onFailed(int resourceId, int statusCode) {

        }

        @Override
        public void onConnectionSuspended(int cause) {
            Log.d(TAG, "onConnectionSuspended() was called with cause: " + cause);
            com.philips.castdemo.videobrowser.utils.Utils.showToast(VideoBrowser.this, R.string.play);
        }

        @Override
        public void onConnectivityRecovered() {
            com.philips.castdemo.videobrowser.utils.Utils.showToast(VideoBrowser.this,
                    R.string.connection_recovered);
        }

        @Override
        public void onCastDeviceDetected(final RouteInfo info) {
            if (!CastPreference.isFtuShown(VideoBrowser.this)) {
                CastPreference.setFtuShown(VideoBrowser.this);

                Log.d(TAG, "Route is visible: " + info);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (mediaRouteMenuItem.isVisible()) {
                            Log.d(TAG, "Cast Icon is visible: " + info.getName());
                            showFtu();
                        }
                    }
                }, 1000);
            }
        }
    };

    setupActionBar(actionBar);
    mCastManager.reconnectSessionIfPossible(this, false);

    videopath = (EditText) findViewById(R.id.video_path);
    videolink = (Spinner) findViewById(R.id.video_link);
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, VIDEO_URL);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    videolink.setAdapter(adapter);
    videolink.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            item_selected = arg2;
            if (VIDEO_URL[item_selected] != null) {
                mPath = VIDEO_URL[item_selected];
            }
            videopath.setText(mPath.toCharArray(), 0, mPath.length());
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
    videolink.setVisibility(View.VISIBLE);
}

From source file:com.google.android.libraries.cast.companionlibrary.cast.player.VideoCastControllerFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    sDialogCanceled = false;//  w  w  w  .j ava 2 s. c  o m
    mCastController = (VideoCastController) activity;
    mHandler = new Handler();
    mCastManager = VideoCastManager.getInstance();
}