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:cn.xiongyihui.wificar.Car.java

public void run() {
    Looper.prepare();/*from  ww  w .  j  a v a 2  s.c  o m*/

    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            String url = "http://" + mIp + "/cgi-bin/serial?" + (String) msg.obj;
            URI uri = URI.create(url);

            HttpResponse httpResponse;
            DefaultHttpClient httpClient = new DefaultHttpClient();
            try {
                httpResponse = httpClient.execute(new HttpGet(uri));
            } catch (IOException e) {
                Log.v(TAG, "Unable to connect to car.");

                mState = STATE_UNCONNECTED;

                return;
            }

            char get;
            try {
                get = (char) httpResponse.getEntity().getContent().read();
            } catch (IOException e) {
                Log.v(TAG, "Unkown situation when connecting car.");

                mState = STATE_UNKOWN;
                return;
            }

            mState = mCommandList.indexOf(Character.toString(get));
        }
    };

    changeTo(STATE_STOP);

    Looper.loop();
}

From source file:com.skalski.raspberrycontrol.Activity_GPIO.java

Handler getClientHandler() {

    return new Handler() {
        @Override/*from w w w  .j  a va2s.c om*/
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            JSONObject root;
            JSONArray gpios;
            gpioArray = new ArrayList<Custom_GPIOAdapter>();
            gpioLayout.setRefreshing(false);

            Log.i(LOGTAG, LOGPREFIX + "new message received from server");

            try {

                root = new JSONObject(msg.obj.toString());

                if (root.has(TAG_ERROR)) {

                    String err = getResources().getString(R.string.com_msg_3) + root.getString(TAG_ERROR);
                    Log.e(LOGTAG, LOGPREFIX + root.getString(TAG_ERROR));
                    toast_connection_error(err);

                } else {

                    gpios = root.getJSONArray(TAG_GPIOSTATE);

                    for (int i = 0; i < gpios.length(); i++) {

                        JSONObject gpioss = gpios.getJSONObject(i);

                        int gpio = gpioss.getInt(TAG_GPIO);
                        int value = gpioss.getInt(TAG_VALUE);
                        String direction = gpioss.getString(TAG_DIRECTION);

                        gpioArray.add(new Custom_GPIOAdapter(gpio, value, direction));
                    }

                    if (gpios.length() == 0) {
                        Log.w(LOGTAG, LOGPREFIX + "can't find exported GPIO's on server side");
                        toast_connection_error(getResources().getString(R.string.error_msg_8));
                    }

                    if (gpioPinout.getDrawable().getConstantState() == getResources()
                            .getDrawable(R.drawable.gpio_unknown).getConstantState()) {
                        if (root.has(TAG_REVISION)) {
                            String revision;
                            revision = root.getString(TAG_REVISION);

                            Log.i(LOGTAG, LOGPREFIX + "set new GPIO layout image");

                            if (revision.equals("0002") || revision.equals("0003")) {

                                gpioPinout.setImageResource(R.drawable.gpio_pinout_1);

                            } else if (revision.equals("0004") || revision.equals("0005")
                                    || revision.equals("0006") || revision.equals("0007")
                                    || revision.equals("0008") || revision.equals("0009")
                                    || revision.equals("000d") || revision.equals("000e")
                                    || revision.equals("000f")) {

                                gpioPinout.setImageResource(R.drawable.gpio_pinout_2);

                            } else if (revision.equals("0010") || revision.equals("0011")) {

                                gpioPinout.setImageResource(R.drawable.gpio_pinout_3);

                            } else {
                                Log.wtf(LOGTAG, LOGPREFIX + "your Raspberry Pi board is weird");
                            }
                        }
                    }
                }

            } catch (Exception ex) {
                Log.e(LOGTAG, LOGPREFIX + "received invalid JSON object");
                toast_connection_error(getResources().getString(R.string.error_msg_2));
            }

            setListAdapter(new Custom_GPIOArrayAdapter(getApplicationContext(), gpioArray));
        }
    };
}

From source file:com.facebook.samples.musicdashboard.MusicGalleryFragment.java

void fetchMusic() {
    // Kill any current downloads
    if (downloadThread != null) {
        downloadThread.quit();//from w w  w.  jav a  2 s  . c  om
        downloadThread = null;
    }

    songs = new ArrayList<Song>();

    Context c = getActivity().getApplicationContext();
    final MusicFetcher fetcher = new MusicFetcher(c);

    // The handler for song image/info download
    Handler handler = new Handler();
    // The listener for song image/info download
    SongImageDownloadListener listener = new SongImageDownloadListener() {
        public void onSongImageUpdated() {
            if (null == adapter)
                return;
            // Notify the GridView that data has changed
            adapter.notifyDataSetChanged();
        }
    };

    // The thread to download song image info
    downloadThread = new SongFetcherThread("SongImage", c, handler, listener);
    downloadThread.start();

    final Handler mHandler = new Handler();
    // Facebook - Graph API request for the music.listens info
    MusicDashboardApplication.mAsyncRunner.request("me/music.listens", new BaseRequestListener() {

        @Override
        public void onComplete(final String response, Object state) {
            // Pass the JSON response and get the music info
            songs = fetcher.fetchSongs(response);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // Update the GridView with initial info that does
                    // not include song image and other details that
                    // are about to be downloaded
                    setAdapter(new SongAdapter(songs));

                    // Clear the cache in preparation for image downloads
                    downloadThread.clearSongImages();

                    // For each song that was parsed out in the "fetchSongs"
                    // call, get the song info and image
                    for (Song song : songs) {
                        downloadThread.downloadSongInfo(song);
                        downloadThread.downloadSongImage(song);
                    }
                }
            });

        }

    });
}

From source file:com.app.jdy.ui.CashAdvanceActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cashadvance);
    initView();/*from www. j av a  2  s  .  c om*/

    // ????
    btnConfirmReceiver = new BtnConfirmReceiver();
    IntentFilter intentFilter = new IntentFilter("org.jdy.action.WITHDCASH_BROADCAST");
    CashAdvanceActivity.this.registerReceiver(btnConfirmReceiver, intentFilter);

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            // ?????
            case 1:
                Bundle bundle = msg.getData();

                canWithdCash = bundle.getString("canWithdCash");
                String bankName = bundle.getString("bankName");
                bankCode1 = bundle.getString("bankCode1");
                String bankCode = bundle.getString("bankCode");

                if (StringUtils.isNullOrEmpty(bankName)) {
                    bankName = "?";
                }
                // ?
                textView4.setText(bankName);

                // ?
                textView3.setText("(" + bankCode + ")");
                if (StringUtils.isNullOrEmpty(bankCode)) {
                    textView3.setText("");
                }

                // ??????
                textView2.setText(canWithdCash);

                // ?????
                editText.setText(canWithdCash);

                break;

            // ?????
            case 2:
                if (withdrawCashDialog != null) {
                    withdrawCashDialog.dismiss();
                }
                break;

            // ???????
            case 3:
                Toast.makeText(CashAdvanceActivity.this,
                        "??? " + withdrawresult + " ???", Toast.LENGTH_LONG)
                        .show();

                editText.setText("");
                if (withdrawCashDialog != null) {
                    withdrawCashDialog.dismiss();
                }
                finish();

                break;

            // ??????
            case 0x110:
                Toast.makeText(CashAdvanceActivity.this, "??", Toast.LENGTH_SHORT).show();

                if (withdrawCashDialog != null) {
                    withdrawCashDialog.dismiss();
                }
                break;

            // ????????????
            case 4:
                Toast.makeText(CashAdvanceActivity.this, Constants.NO_INTENT_TIPS, Toast.LENGTH_LONG).show();
                if (withdrawCashDialog != null) {
                    withdrawCashDialog.dismiss();
                }
                break;
            default:
                break;
            }

        }
    };
    addEvents();
}

From source file:com.ncode.android.apps.schedo.iowear.PagerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pager);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    mHandler = new Handler();
    setupViews();/*from   ww  w .  jav a2  s.co m*/

    if (getIntent().hasExtra(HomeListenerService.KEY_SESSION_ID)) {
        mSessionId = getIntent().getExtras().getString(HomeListenerService.KEY_SESSION_ID);
        Utils.LOGD(TAG, "Session received from service: " + mSessionId);

    }

    // if there is any prior persisted answers for this feedback, lets load them.
    mSavedResponses = Utils.getPersistedResponses(this, mSessionId);
    Utils.saveSessionId(this, mSessionId);

    for (int i = 0; i < 4; i++) {
        Utils.LOGD(TAG, "Response " + i + ": " + mSavedResponses[i]);
        if (mSavedResponses[i] > -1) {
            responses.put(i, mSavedResponses[i]);
        }
    }

    final PagerAdapter adapter = new PagerAdapter(getFragmentManager());
    StarFragment fragment0 = StarFragment.newInstance(0, mSavedResponses[0]);
    RadioFragment fragment1 = RadioFragment.newInstance(1, mSavedResponses[1]);
    RadioFragment fragment2 = RadioFragment.newInstance(2, mSavedResponses[2]);
    RadioFragment fragment3 = RadioFragment.newInstance(3, mSavedResponses[3]);

    mFragments.add(fragment0);
    mFragments.add(fragment1);
    mFragments.add(fragment2);
    mFragments.add(fragment3);

    for (FeedbackFragment f : mFragments) {
        f.setOnQuestionListener(this);
        adapter.addFragment(f);
    }

    adapter.addFragment(new SubmitFragment(this));
    mViewPager.setAdapter(adapter);

    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {

        }

        @Override
        public void onPageSelected(int i) {
            clearTimer();
            setIndicator(i);
            if (i == 0) {
                mFragments.get(i).reshowQuestion();
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();
}

From source file:it.cdpaf.helper.DrawableManager.java

public static void fetchDrawableOnThread(final Macrocategory mac, final ImageView imageView,
        final Context ctx) {
    final String urlString = Const.IMAGE_URL + mac.getNomeImmagine();
    if (drawableMap.containsKey(urlString)) {
        imageView.setImageDrawable(drawableMap.get(urlString));
        //product.setImmagine(drawableMap.get(urlString));
    }//ww w. ja  va  2  s . c  o m

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            Drawable dr = (Drawable) message.obj;
            imageView.setImageDrawable(dr);
            mac.setImmagine(dr);
        }
    };

    Thread thread = new Thread() {
        @Override
        public void run() {
            //TODO : set imageView to a "pending" image
            Drawable d = ctx.getResources().getDrawable(R.drawable.ic_launcher);
            Message messagea = handler.obtainMessage(1, d);
            handler.sendMessage(messagea);
            Drawable drawable = fetchDrawable(urlString, ctx);
            Message messageb = handler.obtainMessage(1, drawable);
            handler.sendMessage(messageb);
        }
    };
    thread.start();
}

From source file:org.xbmc.kore.ui.hosts.AddHostFragmentFinish.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (getView() == null)
        return;//from  ww  w.j  a v  a 2  s .  com

    TextView message = (TextView) getView().findViewById(R.id.done_message);
    message.setText(Html.fromHtml(getString(R.string.wizard_done_message)));
    message.setMovementMethod(LinkMovementMethod.getInstance());

    // Finish button
    Button next = (Button) getView().findViewById(R.id.next);
    next.setText(R.string.finish);
    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            listener.onAddHostFinish();
        }
    });

    // Previous button
    Button previous = (Button) getView().findViewById(R.id.previous);
    previous.setText(null);
    previous.setEnabled(false);

    // Check if PVR is enabled for the current host
    HostManager hostManager = HostManager.getInstance(getActivity());
    if (hostManager.getHostInfo() != null) {
        AddHostFragmentFinish.checkPVREnabledAndSetMenuItems(getActivity(), new Handler());
        String prefKey = Settings.KEY_PREF_CHECKED_PVR_ENABLED
                + String.valueOf(hostManager.getHostInfo().getId());
        PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putBoolean(prefKey, true).apply();
    }

    // Start the syncing process
    Intent syncIntent = new Intent(this.getActivity(), LibrarySyncService.class);
    syncIntent.putExtra(LibrarySyncService.SYNC_ALL_MOVIES, true);
    syncIntent.putExtra(LibrarySyncService.SYNC_ALL_TVSHOWS, true);
    syncIntent.putExtra(LibrarySyncService.SYNC_ALL_MUSIC, true);
    syncIntent.putExtra(LibrarySyncService.SYNC_ALL_MUSIC_VIDEOS, true);
    getActivity().startService(syncIntent);

    //        InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    //        imm.hideSoftInputFromWindow(getActivity()
    //                        .getWindow()
    //                        .getDecorView()
    //                        .getRootView()
    //                        .getWindowToken(), 0);
}

From source file:com.cloverstudio.spika.utils.BitmapManager.java

public void queueJob(final String url, final ImageView imageView, final ProgressBar pbLoading) {
    /* Create handler in UI thread. */
    final Handler handler = new Handler() {
        @Override/*  ww w.ja  va  2 s . c  om*/
        public void handleMessage(Message msg) {
            String tag = imageViews.get(imageView);
            if (tag != null && tag.equals(url)) {
                if (msg.obj != null) {
                    if (smallImg) {
                        imageView.setScaleType(ImageView.ScaleType.CENTER);
                    } else {
                        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    }
                    imageView.setImageBitmap((Bitmap) msg.obj);
                    if (pbLoading != null)
                        pbLoading.setVisibility(View.GONE);
                } else {
                    //                  imageView.setImageBitmap(placeholder);
                    imageView.setImageResource(R.drawable.image_stub);
                    if (pbLoading != null)
                        pbLoading.setVisibility(View.GONE);
                }
            }
        }
    };

    pool.submit(new Runnable() {
        @Override
        public void run() {
            final Bitmap bmp = downloadBitmap(url);
            Message message = Message.obtain();
            message.obj = bmp;

            handler.sendMessage(message);
        }
    });
}

From source file:com.njlabs.amrita.aid.info.Calender.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void setCustomResourceForDates() {

    final Handler dataHandler = new Handler();
    (new Thread(new Runnable() {
        @Override/*  www  . j av a2  s. c  o m*/
        public void run() {

            try {

                InputStream icsInput = getAssets().open("ASECalendar.ics");
                CalendarBuilder builder = new CalendarBuilder();
                net.fortuna.ical4j.model.Calendar calendar = builder.build(icsInput);

                for (Object calendarComponentObject : calendar.getComponents()) {
                    CalendarComponent calendarComponent = (CalendarComponent) calendarComponentObject;
                    String title = calendarComponent.getProperty(Property.SUMMARY).getValue();
                    if (title.length() > 4) {
                        Date startDate = parseDate(calendarComponent.getProperty(Property.DTSTART).getValue());
                        Date endDate = parseDate(calendarComponent.getProperty(Property.DTEND).getValue());
                        title = title.replaceAll("^CD\\d\\d:\\s", "").replaceAll("^CD\\d:\\s", "").replace("*",
                                "");

                        int color = R.color.calendar_green;

                        if (containsAny(title,
                                new String[] { "assessment", "exam", "test", "assesment", "end semester" })) {
                            color = R.color.calendar_red;
                        } else if (containsAny(title,
                                new String[] { "institution day", "amritotsavam", "amritotasavam", "classes",
                                        "working", "instruction", "enrolment", "Birthday", "Talent", "TABLE",
                                        "orientation", "counselling" })) {
                            color = R.color.calendar_blue;
                        } else if (containsAny(title, new String[] { "anokha", "tech fest" })) {
                            color = R.color.calendar_anokha_orange;
                        }

                        Calendar start = Calendar.getInstance();
                        start.setTime(startDate);
                        Calendar end = Calendar.getInstance();
                        end.setTime(endDate);

                        //noinspection WrongConstant
                        if (start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)
                                || end.get(Calendar.DAY_OF_MONTH) == start.get(Calendar.DAY_OF_MONTH) + 1) {
                            backgroundColors.put(startDate, color);
                            textColors.put(startDate, R.color.white);
                            descriptions.put(formatter.format(startDate), title);
                        } else {
                            for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE,
                                    1), date = start.getTime()) {
                                backgroundColors.put(date, color);
                                textColors.put(date, R.color.white);
                                descriptions.put(formatter.format(date), title);
                            }
                        }
                    }
                }

            } catch (Exception e) {
                FirebaseCrash.report(e);
            }

            dataHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (caldroidFragment != null) {
                        caldroidFragment.setBackgroundResourceForDates(backgroundColors);
                        caldroidFragment.setTextColorForDates(textColors);
                        caldroidFragment.refreshView();
                        findViewById(R.id.calendar_holder).setVisibility(View.VISIBLE);
                        findViewById(R.id.progress).setVisibility(View.GONE);
                    }
                }
            });
        }
    })).start();
}

From source file:com.dattasmoon.pebble.plugin.EditNotificationActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_notification);
    mHandler = new Handler();

    lvPackages = (ListView) findViewById(R.id.listPackages);
    spMode = (Spinner) findViewById(R.id.spMode);
    tvTaskerNotice = (TextView) findViewById(R.id.tvTaskerNotice);
    findViewById(R.id.tvAccessibilityError).setOnClickListener(new OnClickListener() {
        @Override/*from  www .  j a  v a  2  s  .c om*/
        public void onClick(View v) {
            startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
        }
    });

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.mode_choices,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spMode.setAdapter(adapter);
    spMode.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            mMode = Constants.Mode.values()[pos];
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            mMode = Constants.Mode.OFF;
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Mode is: off");
            }
        }
    });

}