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.safecell.LoginActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_layout);

    getWindow().setWindowAnimations(R.anim.null_animation);

    InitUi();//from   w  w w. j  a v a  2 s  .  c o  m
    context = LoginActivity.this;
    if (!isTermsAcepted)
        dialogforWebview();

    progressDialog = new ProgressDialog(context);
    mThread = new ProgressThread();
    mThread1 = new ProgressThread1();
    PackageManager pm = getPackageManager();
    try {
        // ---get the package info---
        PackageInfo pi = pm.getPackageInfo("com.safecell", 0);
        // Log.v("Version Code", "Code = "+pi.versionCode);
        // Log.v("Version Name", "Name = "+pi.versionName);
        versionName = pi.versionName;

    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                progressDialog.dismiss();
            } catch (Exception e) {
                Log.e(TAG, "Exception while dismissing progress dialog");
                e.printStackTrace();
            }
            if (mThread.isAlive()) {
                mThread = new ProgressThread();
            }
        }
    };
    handler1 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            progressDialog.dismiss();
            if (mThread1.isAlive()) {
                mThread1 = new ProgressThread1();
            }
        }
    };
}

From source file:com.vuzix.samplewebrtc.android.SessionChannel.java

private synchronized void open() {
    close();//from  w  w  w . j  av  a  2s .  co  m

    // ???
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            mSendHandler = new Handler();
            Looper.loop();
        }
    }.start();

    mConnectionThread = new ConnectionThread();
    mConnectionThread.start();
}

From source file:com.binroot.fatpita.BitmapManager.java

public void fetchBitmapOnThread(final String urlString, final ImageView imageView,
        final ProgressBar indeterminateProgressBar, final Activity act, final boolean saveToHistory) {
    SoftReference<Bitmap> ref = mCache.get(urlString);
    if (ref != null && ref.get() != null) {
        imageView.setImageBitmap(ref.get());
        return;/*  www .  j  a  v  a 2  s .c  om*/
    }

    final Runnable progressBarShow = new Runnable() {
        public void run() {
            if (indeterminateProgressBar != null) {
                imageView.setVisibility(View.GONE);
                indeterminateProgressBar.setVisibility(View.VISIBLE);
            }
        }
    };
    final Runnable progressBarHide = new Runnable() {
        public void run() {
            if (indeterminateProgressBar != null) {
                indeterminateProgressBar.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
            }
        }
    };

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            if (indeterminateProgressBar != null && act != null)
                act.runOnUiThread(progressBarHide);
            imageView.setImageBitmap((Bitmap) message.obj);
        }
    };

    Thread thread = new Thread() {
        @Override
        public void run() {
            if (indeterminateProgressBar != null && act != null)
                act.runOnUiThread(progressBarShow);
            Bitmap bitmap = fetchBitmap(urlString, saveToHistory);
            Message message = handler.obtainMessage(1, bitmap);
            handler.sendMessage(message);
        }
    };
    thread.start();
}

From source file:com.nokia.example.capturetheflag.Controller.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSelf = this;
    mUIHandler = new Handler();
    setRetainInstance(true);/*  w w  w.  ja va 2s  .  com*/
    mSocketClient = new SocketIONetworkClient();
    mClient = mSocketClient;
    mClient.setListener(this);
    mClient.connect(Settings.getServerUrl(getActivity()), Settings.getServerPort(getActivity()));
    mOfflineClient = new OfflineClient();
    mOfflineClient.setListener(this);

    mLocationManager = LocationManagerFactory.getInstance(getActivity());
    mLocationManager.setListener(this);

    NotificationsManagerFactory.getInstance(getActivity()).register();
}

From source file:com.echopf.ECHOTreeMap.java

/**
 * Does Fetch data from the remote server in a background thread.
 *
 * @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 fetching is completed
 * @throws ECHOException //  w w  w  .  jav a 2s. com
 */
protected void doFetch(final boolean sync, final FetchCallback<S> callback) throws ECHOException {
    final Handler handler = new Handler();

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Object> communictor = new Callable<Object>() {

        @Override
        public Object call() throws ECHOException {

            ECHOException exception = null;
            JSONObject data = null;

            try {

                synchronized (lock) {
                    data = ECHOQuery.getRequest(getRequestURLPath());
                    copyData(data);
                }

            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;
                    handler.post(new Runnable() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void run() {
                            callback.done((S) ECHOTreeMap.this, 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.mobicage.rogerthat.registration.YSAAARegistrationActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    T.UI();/*  www.j  a  v a 2  s  .c  o  m*/
    createWorkerThread();
    mUIHandler = new Handler();
    T.setUIThread("YSAAARegistrationActivity.onCreate()");
    mHttpClient = HTTPUtil.getHttpClient(HTTP_TIMEOUT, HTTP_RETRY_COUNT);

    // TODO: This has to be improved.
    // If the app relies on GCM the user should not be able to register.
    if (CloudConstants.USE_GCM_KICK_CHANNEL)
        GoogleServicesUtils.checkPlayServices(this);
}

From source file:com.github.chenxiaolong.dualbootpatcher.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawer_layout);

    mHandler = new Handler();

    mPrefs = getSharedPreferences("settings", 0);

    if (savedInstanceState != null) {
        mTitle = savedInstanceState.getInt(EXTRA_TITLE);
    }//from w  ww  . j  a  v  a  2  s .c  om

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        @Override
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);

            if (mPending != null) {
                mHandler.post(mPending);
                mPending = null;
            }
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
    }

    mDrawerView = (NavigationView) findViewById(R.id.left_drawer);
    mDrawerView.setNavigationItemSelectedListener(this);

    // There's a weird performance issue when the drawer is first opened, no matter if we set
    // the background on the nav header RelativeLayout, set the image on an ImageView, or use
    // Picasso to do either asynchronously. By accident, I noticed that using Picasso's resize()
    // method with any dimensions (even the original) works around the performance issue. Maybe
    // something doesn't like PNGs exported from GIMP?
    View header = mDrawerView.inflateHeaderView(R.layout.nav_header);
    ImageView navImage = (ImageView) header.findViewById(R.id.nav_header_image);
    BitmapFactory.Options dimensions = new BitmapFactory.Options();
    dimensions.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getResources(), R.drawable.material, dimensions);
    Picasso.with(this).load(R.drawable.material).resize(dimensions.outWidth, dimensions.outHeight)
            .into(navImage);

    // Set nav drawer header text
    TextView appName = (TextView) header.findViewById(R.id.nav_header_app_name);
    appName.setText(BuildConfig.APP_NAME_RESOURCE);
    TextView appVersion = (TextView) header.findViewById(R.id.nav_header_app_version);
    appVersion.setText(String.format(getString(R.string.version), BuildConfig.VERSION_NAME));

    // Nav drawer width according to material design guidelines
    // http://www.google.com/design/spec/patterns/navigation-drawer.html
    // https://medium.com/sebs-top-tips/material-navigation-drawer-sizing-558aea1ad266
    final Display display = getWindowManager().getDefaultDisplay();
    final Point size = new Point();
    display.getSize(size);

    final ViewGroup.LayoutParams params = mDrawerView.getLayoutParams();
    int toolbarHeight = getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);
    params.width = Math.min(size.x - toolbarHeight, 6 * toolbarHeight);
    mDrawerView.setLayoutParams(params);

    if (savedInstanceState != null) {
        mFragment = savedInstanceState.getInt(EXTRA_FRAGMENT);

        showFragment();

        mDrawerItemSelected = savedInstanceState.getInt(EXTRA_SELECTED_ITEM);
    } else {
        String[] initialScreens = getResources().getStringArray(R.array.initial_screen_entry_values);
        String initialScreen = mPrefs.getString("initial_screen", null);
        if (initialScreen == null || !ArrayUtils.contains(initialScreens, initialScreen)) {
            initialScreen = INITIAL_SCREEN_ABOUT;
            Editor e = mPrefs.edit();
            e.putString("initial_screen", initialScreen);
            e.apply();
        }

        int navId;
        switch (initialScreen) {
        case INITIAL_SCREEN_ABOUT:
            navId = R.id.nav_about;
            break;
        case INITIAL_SCREEN_ROMS:
            navId = R.id.nav_roms;
            break;
        case INITIAL_SCREEN_PATCHER:
            navId = R.id.nav_patch_zip;
            break;
        default:
            throw new IllegalStateException("Invalid initial screen value");
        }

        // Show about screen by default
        mDrawerItemSelected = navId;
    }

    onDrawerItemClicked(mDrawerItemSelected, false);

    refreshOptionalItems();

    // Open drawer on first start
    new Thread() {
        @Override
        public void run() {
            boolean isFirstStart = mPrefs.getBoolean("first_start", true);
            if (isFirstStart) {
                mDrawerLayout.openDrawer(mDrawerView);
                Editor e = mPrefs.edit();
                e.putBoolean("first_start", false);
                e.apply();
            }
        }
    }.start();
}

From source file:com.example.pyrkesa.shwc.LoginActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_log);//from w w w  .  j  a va  2 s .  c  o m

    final ModelFactory model = (ModelFactory) ModelFactory.getContext();
    UserAuthenticate = model.UserAuthenticate;
    //For settings option-- put it in the first acticity on the onCreate function
    if (getIntent().getBooleanExtra("Exit me", false)) {

        finish();
    }

    if (LoginActivity.UserAuthenticate) {
        Intent homepage = new Intent(getApplicationContext(), MainActivity.class);
        homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(homepage);
        finish();
    }

    final Handler searchipHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String shwcipadress = msg.getData().getString("ip");
            if (shwcipadress != null) {
                if (LoginActivity.UserAuthenticate == false) {
                    LoginActivity.shwcserverFound = true;
                    LoginActivity.url_all_box = "http://" + shwcipadress
                            + "/SHWCDataManagement/Box/get_all_box.php";
                    LoginActivity.url_authenticate = "http://" + shwcipadress
                            + "/SHWCDataManagement/Users/authenticate.php";
                    LoginActivity.url_authenticateByDevice = "http://" + shwcipadress
                            + "/SHWCDataManagement/Users/authenticateByDevice.php";

                    Log.d("SHWCServer", "IP=" + shwcipadress);

                    String android_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

                    Log.d("Android id :", android_id);

                    ArrayList<String> Logs1 = new ArrayList<String>();
                    Logs1.add(url_authenticateByDevice);
                    Logs1.add(android_id);
                    Logs1.add(url_all_box);
                    new AuthenticateUserByDevice().execute(Logs1);
                }
            }

        }
    };

    // Run the ServiceNSD to find the shwcserver
    //final FindServicesNSD zeroconf=new FindServicesNSD((NsdManager)getSystemService(NSD_SERVICE), "_http._tcp",searchipHandler);
    //zeroconf.run();
    // LoginActivity.x=zeroconf;

    // simulation dcouverte serveur shwc
    LoginActivity.shwcserverFound = true;
    model.api_url = "http://" + "10.0.1.5" + "/SHWCDataManagement/";
    LoginActivity.url_all_box = model.api_url + "Box/get_all_box.php";
    LoginActivity.url_authenticate = model.api_url + "Users/authenticate.php";
    LoginActivity.url_authenticateByDevice = model.api_url + "Users/authenticateByDevice.php";

    String android_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
    Log.d("Android id :", android_id);

    ArrayList<String> Logs1 = new ArrayList<String>();
    Logs1.add(url_authenticateByDevice);
    Logs1.add(android_id);
    Logs1.add(url_all_box);

    if (getIntent().hasExtra("logout")) {
        new LoadAllBoxes().execute(url_all_box);
    } else {
        new AuthenticateUserByDevice().execute(Logs1);
    }

    /// end simulation

    LogInButton = ((ImageButton) this.findViewById(R.id.LogInButton));
    // Get login and password from EditText
    final EditText login = ((EditText) this.findViewById(R.id.login));
    final EditText password = ((EditText) this.findViewById(R.id.password));
    final Spinner box_choice = ((Spinner) this.findViewById(R.id.box_choice));

    LogInButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (LoginActivity.shwcserverFound) {
                String pass = password.getText().toString();
                String log = login.getText().toString();
                String box = box_choice.getSelectedItem().toString();

                String android_id1 = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
                ArrayList<String> Logs = new ArrayList<String>();
                Logs.add(log);
                Logs.add(pass);
                Logs.add(url_authenticate);
                Logs.add(android_id1);
                Logs.add(box);
                new AuthenticateUser().execute(Logs);
            } else {
                Toast.makeText(LoginActivity.this, "Systme SHWC indisponible !", Toast.LENGTH_LONG).show();
            }

        }
    });
    // on seleting single product
    // launching Edit Product Screen

}

From source file:net.homelinux.penecoptero.android.citybikes.donation.app.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from   w w w. j  a  v a 2 s  .c  o  m*/
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    mapView = (MapView) findViewById(R.id.mapview);
    mSlidingDrawer = (StationSlidingDrawer) findViewById(R.id.drawer);
    infoLayer = (InfoLayer) findViewById(R.id.info_layer);
    scale = getResources().getDisplayMetrics().density;
    //Log.i("CityBikes","ON CREATEEEEEEEEE!!!!!");
    infoLayerPopulator = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == InfoLayer.POPULATE) {
                infoLayer.inflateStation(stations.getCurrent());

            }
            if (msg.what == CityBikes.BOOKMARK_CHANGE) {
                int id = msg.arg1;
                boolean bookmarked;
                if (msg.arg2 == 0) {
                    bookmarked = false;
                } else {
                    bookmarked = true;
                }
                StationOverlay station = stations.getById(id);
                try {
                    BookmarkManager bm = new BookmarkManager(getApplicationContext());
                    bm.setBookmarked(station.getStation(), !bookmarked);
                } catch (Exception e) {
                    Log.i("CityBikes", "Error bookmarking station");
                    e.printStackTrace();
                }

                if (!view_all) {
                    view_near();
                }
                mapView.postInvalidate();
            }
        }
    };

    infoLayer.setHandler(infoLayerPopulator);
    RelativeLayout.LayoutParams zoomControlsLayoutParams = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    zoomControlsLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    zoomControlsLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

    mapView.addView(mapView.getZoomControls(), zoomControlsLayoutParams);

    modeButton = (ToggleButton) findViewById(R.id.mode_button);

    modeButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            changeMode(!getBike);
        }

    });

    applyMapViewLongPressListener(mapView);

    settings = getSharedPreferences(CityBikes.PREFERENCES_NAME, 0);

    List<Overlay> mapOverlays = mapView.getOverlays();

    locator = new Locator(this, new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == Locator.LOCATION_CHANGED) {
                GeoPoint point = new GeoPoint(msg.arg1, msg.arg2);
                hOverlay.moveCenter(point);
                mapView.getController().animateTo(point);
                mDbHelper.setCenter(point);
                // Location has changed
                try {
                    mDbHelper.updateDistances(point);
                    infoLayer.update();
                    if (!view_all) {
                        view_near();
                    }
                } catch (Exception e) {

                }
                ;
            }
        }
    });

    hOverlay = new HomeOverlay(locator.getCurrentGeoPoint(), new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == HomeOverlay.MOTION_CIRCLE_STOP) {
                try {
                    if (!view_all) {
                        view_near();
                    }
                    mapView.postInvalidate();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    });

    stations = new StationOverlayList(mapOverlays, new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //Log.i("CityBikes","Message: "+Integer.toString(msg.what)+" "+Integer.toString(msg.arg1));
            if (msg.what == StationOverlay.TOUCHED && msg.arg1 != -1) {
                // One station has been touched
                stations.setCurrent(msg.arg1, getBike);
                infoLayer.inflateStation(stations.getCurrent());
                //Log.i("CityBikes","Station touched: "+Integer.toString(msg.arg1));
            }
        }
    });

    stations.addOverlay(hOverlay);

    mNDBAdapter = new NetworksDBAdapter(getApplicationContext());

    mDbHelper = new StationsDBAdapter(this, mapView, new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case StationsDBAdapter.FETCH:
                break;
            case StationsDBAdapter.UPDATE_MAP:
                progressDialog.dismiss();
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("reload_network", false);
                editor.commit();
            case StationsDBAdapter.UPDATE_DATABASE:
                StationOverlay current = stations.getCurrent();
                if (current == null) {
                    infoLayer.inflateMessage(getString(R.string.no_bikes_around));
                }
                if (current != null) {
                    current.setSelected(true, getBike);
                    infoLayer.inflateStation(current);
                    if (view_all)
                        view_all();
                    else
                        view_near();
                } else {

                }
                mapView.invalidate();
                infoLayer.update();
                ////Log.i("openBicing", "Database updated");
                break;
            case StationsDBAdapter.NETWORK_ERROR:
                ////Log.i("openBicing", "Network error, last update from " + mDbHelper.getLastUpdated());
                Toast toast = Toast.makeText(getApplicationContext(),
                        getString(R.string.network_error) + " " + mDbHelper.getLastUpdated(),
                        Toast.LENGTH_LONG);
                toast.show();
                break;
            }
        }
    }, stations);

    mDbHelper.setCenter(locator.getCurrentGeoPoint());

    mSlidingDrawer.setHandler(new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case StationSlidingDrawer.ITEMCLICKED:
                StationOverlay clicked = (StationOverlay) msg.obj;
                stations.setCurrent(msg.arg1, getBike);
                Message tmp = new Message();
                tmp.what = InfoLayer.POPULATE;
                tmp.arg1 = msg.arg1;
                infoLayerPopulator.dispatchMessage(tmp);
                mapView.getController().animateTo(clicked.getCenter());
            }
        }
    });

    if (savedInstanceState != null) {
        locator.unlockCenter();
        hOverlay.setRadius(savedInstanceState.getInt("homeRadius"));
        this.view_all = savedInstanceState.getBoolean("view_all");
    } else {
        updateHome();
    }

    try {
        mDbHelper.loadStations();
        if (savedInstanceState == null) {
            String strUpdated = mDbHelper.getLastUpdated();

            Boolean dirty = settings.getBoolean("reload_network", false);

            if (strUpdated == null || dirty) {
                this.fillData(view_all);
            } else {
                Toast toast = Toast.makeText(this.getApplicationContext(),
                        "Last Updated: " + mDbHelper.getLastUpdated(), Toast.LENGTH_LONG);
                toast.show();
                Calendar cal = Calendar.getInstance();
                long now = cal.getTime().getTime();
                if (Math.abs(now - mDbHelper.getLastUpdatedTime()) > 60000 * 5)
                    this.fillData(view_all);
            }
        }

    } catch (Exception e) {
        ////Log.i("openBicing", "SHIT ... SUCKS");
    }
    ;

    if (view_all)
        view_all();
    else
        view_near();
    ////Log.i("openBicing", "CREATE!");
}

From source file:com.google.appinventor.components.runtime.TinyWebDB.java

/**
 * Creates a new TinyWebDB component.//from  w  w  w.  j a v a 2 s . c  om
 *
 * @param container the Form that this component is contained in.
 */
public TinyWebDB(ComponentContainer container) {
    super(container.$form());
    // We use androidUIHandler when we set up operations (like
    // postStoreVaue and getStoreValue) that run asynchronously in a
    // separate thread, but which themselves want to cause actions
    // back in the UI thread.  They do this by posting those actions
    // to androidUIHandler.
    androidUIHandler = new Handler();
    // We set the initial value of serviceURL to be the
    // demo Web service.
    serviceURL = "http://appinvtinywebdb.appspot.com/";
}