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.example.activity.ShotListActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (isExit == false) {
            isExit = true;//from ww w.  j  ava  2s  .  com
            ToastView toast = new ToastView(getApplicationContext(), "?BeeExample");
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    isExit = false;
                }
            };
            mHandler.sendEmptyMessageDelayed(0, 3000);
            return true;
        } else {
            finish();
            return false;
        }
    }
    return true;
}

From source file:com.thousandthoughts.tutorials.SensorFusionActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from  w w  w .ja  v  a  2  s.c o  m*/
    layout = (RelativeLayout) findViewById(R.id.mainlayout);
    IP1 = "";
    IP2 = "";
    angle1 = 0.0f;
    angle2 = 0.0f;
    gyroOrientation[0] = 0.0f;
    gyroOrientation[1] = 0.0f;
    gyroOrientation[2] = 0.0f;

    // initialise gyroMatrix with identity matrix
    gyroMatrix[0] = 1.0f;
    gyroMatrix[1] = 0.0f;
    gyroMatrix[2] = 0.0f;
    gyroMatrix[3] = 0.0f;
    gyroMatrix[4] = 1.0f;
    gyroMatrix[5] = 0.0f;
    gyroMatrix[6] = 0.0f;
    gyroMatrix[7] = 0.0f;
    gyroMatrix[8] = 1.0f;

    // get sensorManager and initialise sensor listeners
    mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
    initListeners();

    // wait for one second until gyroscope and magnetometer/accelerometer
    // data is initialised then scedule the complementary filter task
    fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(), 1000, TIME_CONSTANT);

    // GUI stuff
    try {
        client1 = new MyCoapClient(this.IP1);
        client2 = new MyCoapClient(this.IP2);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    json = new JSONObject();
    mHandler = new Handler();
    radioSelection = 0;
    d.setRoundingMode(RoundingMode.HALF_UP);
    d.setMaximumFractionDigits(3);
    d.setMinimumFractionDigits(3);

    /// Application layout here only

    RelativeLayout.LayoutParams left = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams right = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams up = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams down = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams button1 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams button2 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams text1 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams text2 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    ImageView img_left = new ImageView(this);
    ImageView img_right = new ImageView(this);
    ImageView img_up = new ImageView(this);
    ImageView img_down = new ImageView(this);
    ImageView img_button1 = new ImageView(this);
    ImageView img_button2 = new ImageView(this);
    final EditText edittext1 = new EditText(this);
    final EditText edittext2 = new EditText(this);
    img_left.setImageResource(R.drawable.left_button);
    img_right.setImageResource(R.drawable.right_button);
    img_up.setImageResource(R.drawable.up);
    img_down.setImageResource(R.drawable.down);
    img_button1.setImageResource(R.drawable.button);
    img_button2.setImageResource(R.drawable.button);

    left.setMargins(0, 66, 0, 0);
    right.setMargins(360, 66, 0, 0);
    up.setMargins(240, 90, 0, 0);
    down.setMargins(240, 240, 0, 0);
    button1.setMargins(440, 800, 0, 0);
    button2.setMargins(440, 900, 0, 0);
    text1.setMargins(5, 800, 0, 0);
    text2.setMargins(5, 900, 0, 0);

    layout.addView(img_left, left);
    layout.addView(img_right, right);
    layout.addView(img_up, up);
    layout.addView(img_down, down);
    layout.addView(img_button1, button1);
    layout.addView(edittext1, text1);
    layout.addView(img_button2, button2);
    layout.addView(edittext2, text2);

    img_left.getLayoutParams().height = 560;
    img_left.getLayoutParams().width = 280;
    img_right.getLayoutParams().height = 560;
    img_right.getLayoutParams().width = 280;
    img_up.getLayoutParams().height = 150;
    img_up.getLayoutParams().width = 150;
    img_down.getLayoutParams().height = 150;
    img_down.getLayoutParams().width = 150;
    img_button1.getLayoutParams().height = 100;
    img_button1.getLayoutParams().width = 200;
    edittext1.getLayoutParams().width = 400;
    edittext1.setText("84.248.76.84");
    edittext2.setText("84.248.76.84");
    img_button2.getLayoutParams().height = 100;
    img_button2.getLayoutParams().width = 200;
    edittext2.getLayoutParams().width = 400;

    /////////// Define and Remember Position for EACH PHYSICAL OBJECTS (LAPTOPS) /////////////////////
    img_button1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            // TODO Auto-generated method stub
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // POSITION OF LAPTOP 1 IS REMEMBERED
                angle1 = fusedOrientation[0];
                IP1 = edittext1.getText().toString();
                try {
                    // CREATE CLIENT CONNECT TO FIRST LAPTOP
                    client1 = new MyCoapClient(IP1);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                //view.setImageResource(R.drawable.left_button);
                break;
            }
            return true;
        }

    });

    img_button2.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            // TODO Auto-generated method stub
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // POSITION OF LAPTOP 2 IS REMEMBERED
                angle2 = fusedOrientation[0];
                IP2 = edittext2.getText().toString();
                try {
                    // CREATE CLIENT CONNECT TO SECOND LAPTOP
                    client2 = new MyCoapClient(IP2);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                break;
            }
            return true;
        }

    });

    img_left.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.left_button_press);

                ///////////////////// PERFORM CLICK ACTION BASED ON POSITION OF 2 PHYSICAL OBJECTS (LAPTOPs) HERE/////////////////////////

                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0 < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0) {
                        client1.runClient("left pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0 < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0) {
                        client2.runClient("left pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.left_button);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("left released");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("left released");
                    }
                }
                break;
            }
            return true;
        }
    });

    img_right.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.right_button_press);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("right pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("right pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.right_button);
                break;
            }
            return true;
        }
    });

    img_up.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.up_press);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("up pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("up pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.up);
                break;
            }
            return true;
        }
    });

    img_down.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.down_press);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("down pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("down pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.down);
                break;
            }
            return true;
        }
    });
}

From source file:blackman.matt.boardlist.BoardListActivity.java

/**
 * When the activity is created this sets up the activity.
 *
 * @param savedInstanceState The saved state if this was created before.
 *///from w  w w  . j  av a2 s .com
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_board_list);
    mProgress = (LinearLayout) findViewById(R.id.progress_board_list);
    mBoardList = (ListView) findViewById(R.id.lv_board_list);

    initSpinners();

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    Boolean ageAccept = preferences.getBoolean("age_guard_accept", false);

    if (ageAccept && list_db.isEmpty()) {
        new GetBoardList().execute();
    }

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            Cursor cursor = list_db.getSortedSearch(mCurFilter, DEFAULT_SELECTED_COLUMN, DEFAULT_SORT_ORDER);
            mAdapter = new BoardListCursorAdapter(BoardListActivity.this, cursor);
            mAdapter.setListener(BoardListActivity.this);

            mBoardList.setAdapter(mAdapter);
        }
    });
}

From source file:org.jinzora.util.DrawableManager.java

public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
    if (urlString == null) {
        if (DBG)/*from w  w w  . j ava  2  s .c  o m*/
            Log.d(TAG, "Null image url.");
        synchronized (pendingViews) {
            pendingViews.remove(imageView);
        }
        return;
    }

    synchronized (pendingViews) {
        pendingViews.put(imageView, urlString);
    }

    if (drawableMap.containsKey(urlString)) {
        SoftReference<Drawable> reference = drawableMap.get(urlString);
        Drawable drawable = reference.get();
        if (drawable != null) {
            if (DBG)
                Log.d(TAG, "Image cached in memory.");
            imageView.setImageDrawable(drawable);
            return;
        } else {
            if (DBG)
                Log.d(TAG, "Soft reference cleared.");
            drawableMap.remove(urlString);
        }
    }

    File localFile = getLocalFile(urlString);
    if (localFile != null && localFile.exists()) {
        if (DBG)
            Log.d(TAG, "Image from disk.");
        imageView.setImageDrawable(fetchDrawable(urlString));
        return;
    }

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            synchronized (pendingViews) {
                String latest = pendingViews.get(imageView);
                if (urlString.equals(latest)) {
                    imageView.setImageDrawable((Drawable) message.obj);
                }
            }
        }
    };

    new Thread() {
        @Override
        public void run() {
            Drawable drawable = fetchDrawable(urlString);
            Message message = handler.obtainMessage(1, drawable);
            handler.sendMessage(message);
        }
    }.start();
}

From source file:com.breadwallet.presenter.fragments.MainFragmentQR.java

private void setTipsPositions(final View rootView) {
    new Handler().postDelayed(new Runnable() {
        @Override/*  ww w  .  j a v a 2  s.  c  o m*/
        public void run() {
            View temp = rootView.findViewById(R.id.qr_image_address_layout);
            int qrBubble1Position = temp == null ? MainActivity.screenParametersPoint.y / 2
                    : temp.getHeight() / 3 + temp.getHeight() / 10;
            int qrBubble2Position = temp == null ? MainActivity.screenParametersPoint.y / 2
                    : temp.getHeight() - temp.getHeight() / 7;
            BRTipsManager.setQrBubblesPosition(qrBubble1Position, qrBubble2Position);
        }
    }, 200);
}

From source file:com.nextgis.mobile.map.MapBase.java

/**
 * Create handler for messages//w w w.j  ava  2 s .c om
 */
protected void createHandler() {
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Bundle resultData = msg.getData();
            boolean bHasErr = resultData.getBoolean(BUNDLE_HASERROR_KEY);
            if (bHasErr) {
                reportError(resultData.getString(BUNDLE_MSG_KEY));
            } else {
                processMessage(resultData);
            }
        }
    };
}

From source file:com.gsoc.ijosa.liquidgalaxycontroller.PW.UrlDeviceDiscoveryService.java

private void initialize() {
    mNotificationManager = NotificationManagerCompat.from(this);
    mUrlDeviceDiscoverers = new ArrayList<>();

    // disable mDNS PWO discovery for pre-M devices
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
        mUrlDeviceDiscoverers.add(new MdnsUrlDeviceDiscoverer(this));
    }//  w  w w.  jav  a 2  s .  c  o  m
    mUrlDeviceDiscoverers.add(new SsdpUrlDeviceDiscoverer(this));
    mUrlDeviceDiscoverers.add(new BleUrlDeviceDiscoverer(this));
    for (UrlDeviceDiscoverer urlDeviceDiscoverer : mUrlDeviceDiscoverers) {
        urlDeviceDiscoverer.setCallback(this);
    }
    mUrlDeviceDiscoveryListeners = new ArrayList<>();
    mHandler = new Handler();
    mPwCollection = new PhysicalWebCollection();
    mCanUpdateNotifications = false;
}

From source file:com.github.akinaru.roboticbuttonpusher.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;/*w ww  .  jav  a 2  s. c o 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) {

                dispatchBtDevices(device, rssi, scanRecord);
            }
        }
    };
}

From source file:com.spoiledmilk.ibikecph.navigation.routing_engine.SMRoute.java

@Override
public void onResponseReceived(int requestType, Object response) {
    switch (requestType) {
    case SMHttpRequest.REQUEST_GET_ROUTE:
        JsonNode jsonRoot = ((RouteInfo) response).jsonRoot;
        if (jsonRoot == null || jsonRoot.path("status").asInt(-1) != 0) {
            if (listener != null)
                listener.routeNotFound();
        } else {//from w w w . j  ava2s . c o m
            setupRoute(jsonRoot);
            if (listener != null)
                listener.startRoute();
        }
        break;
    case SMHttpRequest.REQUEST_GET_RECALCULATED_ROUTE:
        final JsonNode jRoot = ((RouteInfo) response).jsonRoot;

        if (jRoot == null || jRoot.path("status").asInt() != 0) {
            if (listener != null) {
                listener.serverError();
            }
            recalculationInProgress = false;
            return;
        }

        final Handler h = new Handler();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {

                boolean ok = parseFromJson(jRoot, null, isRouteBroken);

                //                        logWaypoints();

                if (ok) {
                    approachingTurn = false;
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            if (lastLocation != null) {
                                visitLocation(lastLocation);
                            }
                            if (visitedLocations != null && visitedLocations.size() > 0) {
                                // visitLocation(visitedLocations.get(visitedLocations.size() - 1));
                            }
                            if (SMLocationManager.getInstance().hasValidLocation()) {
                                updateDistances(SMLocationManager.getInstance().getLastValidLocation());
                            }
                            if (listener != null) {
                                listener.routeRecalculationDone();
                                listener.updateRoute();
                            }
                            recalculationInProgress = false;
                        }
                    });
                } else {
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            if (listener != null)
                                listener.serverError();
                            recalculationInProgress = false;
                        }
                    });
                }

            }
        });
        t.setPriority(Thread.MIN_PRIORITY);
        t.start();
    }
}

From source file:li.barter.chat.ChatService.java

@Override
public void onCreate() {
    super.onCreate();
    SharedPreferenceHelper.registerSharedPreferencesChangedListener(
            ChatNotificationHelper.getInstance(this).getOnSharedPreferenceChangeListener());
    mChatDateFormatter = new DateFormatter(AppConstants.TIMESTAMP_FORMAT, AppConstants.CHAT_TIME_FORMAT);
    mMessageDateFormatter = new DateFormatter(AppConstants.TIMESTAMP_FORMAT, AppConstants.MESSAGE_TIME_FORMAT);
    mRequestQueue = ((IVolleyHelper) getApplication()).getRequestQueue();
    mVolleyCallbacks = new VolleyCallbacks(mRequestQueue, this);
    mCurrentConnectMultiplier = 0;/*  w  w  w .j av a2s.c om*/
    mHandler = new Handler();
    mChatProcessor = Executors.newSingleThreadExecutor();
    mChatProcessTaskBuilder = new Builder(this);
}