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.newgxu.android.notty.ui.LoginBoxFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    View v = LayoutInflater.from(getActivity()).inflate(R.layout.login, null);
    final EditText account = (EditText) v.findViewById(R.id.account);
    final EditText pwd = (EditText) v.findViewById(R.id.password);
    return new AlertDialog.Builder(getActivity()).setCancelable(false).setTitle(R.string.login_box)
            .setIcon(StyleUtils.getThemeDependentAttr(getActivity().getTheme(), R.attr.user_icon)).setView(v)
            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override/* ww w  .  j a  v  a 2s.  c o m*/
                public void onClick(DialogInterface dialog, int which) {
                    progressDialog = ProgressDialog.show(getActivity(), "login...", "login...");
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            String _account = account.getEditableText().toString();
                            String _pwd = pwd.getEditableText().toString();
                            NottyApplication app = NottyApplication.getApp();
                            SharedPreferences prefs = app.getPrefs();
                            try {
                                JSONObject result = RESTMethod
                                        .get(C.DOMAIN + "/info/login?account=" + _account + "&pwd=" + _pwd);
                                if (result.getInt(C.STATUS) == C.OK) {
                                    //                              put the account and pwd to the app' s context.
                                    SharedPreferences.Editor editor = NottyApplication.getApp().getPrefs()
                                            .edit();
                                    editor.putString(C.ACCOUNT, _account);
                                    editor.putString(C.PWD, _pwd);
                                    JSONObject u = result.getJSONObject(C.USER);
                                    editor.putLong(C._ID, u.getLong(C.ID));
                                    editor.putString(C.user.AUTHED_NAME, u.getString(C.user.AUTHED_NAME));
                                    editor.commit();
                                    Toast.makeText(getActivity(), R.string.login_ok, Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(getActivity(), UserServiceActivity.class);
                                    startActivity(intent);
                                } else {
                                    Toast.makeText(getActivity(),
                                            getString(R.string.login_no) + ": " + result.getString(C.MSG),
                                            Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                L.wtf(TAG, "error when try to login in the thread.", e);
                            }
                        }
                    });
                    progressDialog.dismiss();

                    //                  new Thread(new Runnable() {
                    //                     @Override
                    //                     public void run() {
                    //                        try {
                    //                           Thread.sleep(3000);
                    //                           JSONObject result = RESTMethod.get(C.DOMAIN
                    //                                 + "/info/login?account=" + _account + "&pwd=" + _pwd);
                    //                           if (result.getInt(C.STATUS) == C.OK) {
                    ////                              put the account and pwd to the app' s context.
                    //                              SharedPreferences.Editor editor = NottyApplication.getApp().getPrefs().edit();
                    //                              editor.putString(C.ACCOUNT, _account);
                    //                              editor.putString(C.PWD, _pwd);
                    //                              editor.commit();
                    //                              Toast.makeText(getActivity(), R.string.login_ok, Toast.LENGTH_SHORT).show();
                    //                           } else {
                    //                              Toast.makeText(getActivity(), R.string.login_no + ": "
                    //                                    + result.getString(C.MSG), Toast.LENGTH_SHORT).show();
                    //                           }
                    //                        } catch (Exception e) {
                    //                           L.wtf(TAG, "error when try to login in the thread.", e);
                    //                        } finally {
                    //                           progressDialog.dismiss();
                    //                        }
                    //                     }
                    //                  }).start();
                }
            }).setNegativeButton(R.string.no, null).create();
}

From source file:com.github.bcfurtado.copaapp.util.DrawableManager.java

/**
 * Carrega a imagem a partir de uma url em uma thread separada da thread da interface.
 * @param urlString indica a url da imagem
 * @param imageView indica a imagemView a qual  imagem vai ser associada ao ser carregada.
 *//*from www . ja  va2 s  .  c om*/
public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
    if (drawableMap.containsKey(urlString)) {
        imageView.setImageDrawable(drawableMap.get(urlString));
    }

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

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

From source file:br.com.devfest.norte.wear.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();/*  w  ww .j  ava2s . c o m*/

    if (getIntent().hasExtra(HomeListenerService.KEY_SESSION_ID)) {
        mSessionId = getIntent().getExtras().getString(HomeListenerService.KEY_SESSION_ID);
        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++) {
        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:net.networksaremadeofstring.rhybudd.DiagnosticActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_diagnostics);
    try {//  w  w  w . j a va  2  s.c o m
        getActionBar().setTitle("Diagnostics App");
        getActionBar().setSubtitle("Helps to pin point any problems getting events");
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    } catch (Exception e) {

    }

    DiagnosticOutput = (TextView) findViewById(R.id.DiagOutput);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    ((Button) findViewById(R.id.StartDiagButton)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            findViewById(R.id.progressBar2).setVisibility(View.VISIBLE);
            DiagnosticOutput.setText("");
            DoDiagnostics();
            view.setEnabled(false);
        }
    });

    progressHandler = new Handler() {
        public void handleMessage(Message msg) {
            try {
                DiagnosticOutput.setText(DiagnosticOutput.getText().toString()
                        + msg.getData().getString(DIAGNOSTIC_OUTPUT) + "\n");
            } catch (Exception e) {
                DiagnosticOutput.setText(DiagnosticOutput.getText().toString()
                        + "A diagnostic message was received but there was an issue displaying it\n");
            }

            if (msg.what == DIAGNOSTIC_PRE) {
                try {
                    if (progressBar.getSecondaryProgress() < 20)
                        progressBar.setSecondaryProgress((progressBar.getSecondaryProgress() + 1));
                } catch (Exception e) {

                }
            } else if (msg.what == DIAGNOSTIC_SUCCESS) {
                try {
                    if (progressBar.getProgress() < 20)
                        progressBar.setProgress((progressBar.getProgress() + 1));
                } catch (Exception e) {

                }
            } else if (msg.what == DIAGNOSTIC_FAILURE) {
                try {
                    DiagnosticOutput.setTextColor(getResources().getColor(R.color.WarningRed));
                    findViewById(R.id.progressBar2).setVisibility(View.INVISIBLE);
                    findViewById(R.id.StartDiagButton).setEnabled(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (msg.what == DIAGNOSTIC_COMPLETE) {
                try {
                    DiagnosticOutput.setTextColor(Color.rgb(50, 102, 50));
                    progressBar.setProgress(20);
                    findViewById(R.id.progressBar2).setVisibility(View.INVISIBLE);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    Toast.makeText(DiagnosticActivity.this, "Diagnostics Complete!", Toast.LENGTH_SHORT).show();
                    findViewById(R.id.StartDiagButton).setEnabled(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //Not much else
            }

            try {
                progressBar.invalidate();
            } catch (Exception e) {

            }
        }
    };
}

From source file:io.samsungsami.example.SAMInBLEws.SAMISession.java

private SAMISession() {
    if (Looper.myLooper() != Looper.getMainLooper()) {
        Log.e(TAG, "Constructor is not called in UI thread ");
    }// w  w w . j a va 2s.c  o m
    mHandler = new Handler();
}

From source file:eu.loopit.f2011.library.BitmapManager.java

public void fetchBitmapOnThread(final String urlString, final ImageView imageView, final Bitmap defaultImage) {
    if (bitmapMap.containsKey(urlString)) {
        imageView.setImageBitmap(bitmapMap.get(urlString));
    }//www  .ja va 2 s .com

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

    Thread thread = new Thread() {
        @Override
        public void run() {
            Bitmap bitmap = fetchBitmap(urlString, defaultImage);
            Message message = handler.obtainMessage(1, bitmap);
            handler.sendMessage(message);
        }
    };
    thread.start();
}

From source file:fi.hut.soberit.sensors.uploaders.PhysicalActivityUploader.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand");
    int res = super.onStartCommand(intent, flags, startId);

    if (intent == null) {
        return res;
    }//w w w .ja v  a 2 s  . c  om

    pulseType = types.get(DriverInterface.TYPE_PULSE);
    accelerationType = types.get(DriverInterface.TYPE_ACCELEROMETER);

    handler = new Handler();

    handler.postDelayed(updater, UploadRecords.UPLOAD_FREQUENCY);

    return res;
}

From source file:com.samknows.measurement.activity.SamKnowsActivating.java

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

    setContentView(R.layout.activating);
    Util.initializeFonts(this);
    Util.overrideFonts(this, findViewById(android.R.id.content));

    /*//from   w  w  w . ja v  a  2s.co m
     * {"type":"mainprogress", "value":"42"} {"type":"activating"}
     * {"type":"download"} {"type":"inittests", "total":"24",
     * "finished":"21", "currentbest":"london", "besttime": "25 ms"}
     * {"type":"completed"}
     */

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            TextView tv;

            JSONObject message_json;
            if (msg.obj == null) {
                return;
            }
            message_json = (JSONObject) msg.obj;

            try {
                String type = message_json.getString(UIUpdate.JSON_TYPE);

                if (type == UIUpdate.JSON_MAINPROGRESS) {
                    String value = message_json.getString(UIUpdate.JSON_VALUE);
                    ProgressBar progressbar = (ProgressBar) findViewById(R.id.activation_progress);
                    int progress = Integer.parseInt(value);
                    progressbar.setProgress(progress);
                } else if (type == UIUpdate.JSON_ACTIVATED) {
                    ProgressBar pb = (ProgressBar) findViewById(R.id.activating_progress);
                    pb.setVisibility(View.GONE);
                    ImageView iv = (ImageView) findViewById(R.id.activating_complete);
                    iv.setVisibility(View.VISIBLE);
                } else if (type == UIUpdate.JSON_DOWNLOADED) {
                    ProgressBar pb = (ProgressBar) findViewById(R.id.download_progress);
                    pb.setVisibility(View.GONE);
                    ImageView iv = (ImageView) findViewById(R.id.download_complete);
                    iv.setVisibility(View.VISIBLE);
                } else if (type == UIUpdate.JSON_INITTESTS) {
                    String total = message_json.getString(UIUpdate.JSON_TOTAL);
                    String finished = message_json.getString(UIUpdate.JSON_FINISHED);
                    String currentbest = message_json.getString(UIUpdate.JSON_CURRENTBEST);
                    String besttime = message_json.getString(UIUpdate.JSON_BESTTIME);
                    tv = (TextView) findViewById(R.id.currentbest);
                    tv.setText(currentbest);
                    tv = (TextView) findViewById(R.id.besttime);
                    tv.setText(besttime);
                    tv = (TextView) findViewById(R.id.server_status);
                    tv.setText(finished + " " + getString(R.string.of) + " " + total);

                } else if (type == UIUpdate.JSON_COMPLETED) {
                    LoginHelper.openMainScreen(SamKnowsActivating.this);
                    SamKnowsActivating.this.finish();
                }

            } catch (JSONException e) {
                Logger.e(SamKnowsActivating.class, "Error in parsing JSONObject: " + e.getMessage());

            }

        }
    };
    if (MainService.registerHandler(handler)) {
        Logger.d(this, "handler registered");
    } else {
        Logger.d(this, "MainService is not executing");
        LoginHelper.openMainScreen(SamKnowsActivating.this);
        SamKnowsActivating.this.finish();

    }
}

From source file:net.networksaremadeofstring.cyllell.ViewRoles_Fragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    list = (ListView) this.getActivity().findViewById(R.id.rolesListView);
    settings = this.getActivity().getSharedPreferences("Cyllell", 0);
    try {//from w  ww  .  j a  va  2 s. c  o m
        Cut = new Cuts(getActivity());
    } catch (Exception e) {
        e.printStackTrace();
    }

    dialog = new ProgressDialog(getActivity());
    dialog.setTitle("Contacting Chef");
    dialog.setMessage("Please wait: Prepping Authentication protocols");
    dialog.setIndeterminate(true);
    if (listOfRoles.size() < 1) {
        dialog.show();
    }

    updateListNotify = new Handler() {
        public void handleMessage(Message msg) {
            int tag = msg.getData().getInt("tag", 999999);

            if (msg.what == 0) {
                if (tag != 999999) {
                    listOfRoles.get(tag).SetSpinnerVisible();
                }
            } else if (msg.what == 1) {
                //Get rid of the lock
                CutInProgress = false;

                //the notifyDataSetChanged() will handle the rest
            } else if (msg.what == 99) {
                if (tag != 999999) {
                    Toast.makeText(ViewRoles_Fragment.this.getActivity(),
                            "An error occured during that operation.", Toast.LENGTH_LONG).show();
                    listOfRoles.get(tag).SetErrorState();
                }
            }
            RoleAdapter.notifyDataSetChanged();
        }
    };

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            //Once we've checked the data is good to use start processing it
            if (msg.what == 0) {
                OnClickListener listener = new OnClickListener() {
                    public void onClick(View v) {
                        GetMoreDetails((Integer) v.getTag());
                    }
                };

                OnLongClickListener listenerLong = new OnLongClickListener() {
                    public boolean onLongClick(View v) {
                        selectForCAB((Integer) v.getTag());
                        return true;
                    }
                };

                RoleAdapter = new RoleListAdaptor(getActivity(), listOfRoles, listener, listenerLong);
                list = (ListView) getView().findViewById(R.id.rolesListView);
                if (list != null) {
                    if (RoleAdapter != null) {
                        list.setAdapter(RoleAdapter);
                    } else {
                        //Log.e("CookbookAdapter","CookbookAdapter is null");
                    }
                } else {
                    //Log.e("List","List is null");
                }

                dialog.dismiss();
            } else if (msg.what == 200) {
                dialog.setMessage("Sending request to Chef...");
            } else if (msg.what == 201) {
                dialog.setMessage("Parsing JSON.....");
            } else if (msg.what == 202) {
                dialog.setMessage("Populating UI!");
            } else {
                //Close the Progress dialog
                dialog.dismiss();

                //Alert the user that something went terribly wrong
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setTitle("API Error");
                alertDialog.setMessage("There was an error communicating with the API:\n"
                        + msg.getData().getString("exception"));
                alertDialog.setButton2("Back", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //getActivity().finish();
                    }
                });
                alertDialog.setIcon(R.drawable.icon);
                alertDialog.show();
            }
        }
    };

    Thread dataPreload = new Thread() {
        public void run() {
            if (listOfRoles.size() > 0) {
                handler.sendEmptyMessage(0);
            } else {
                try {
                    handler.sendEmptyMessage(200);
                    Roles = Cut.GetRoles();
                    handler.sendEmptyMessage(201);

                    JSONArray Keys = Roles.names();

                    for (int i = 0; i < Keys.length(); i++) {
                        listOfRoles.add(new Role(Keys.getString(i), Roles.getString(Keys.getString(i))
                                .replaceFirst("^(https://|http://).*/roles/", "")));
                    }

                    handler.sendEmptyMessage(202);
                    handler.sendEmptyMessage(0);
                } catch (Exception e) {
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString("exception", e.getMessage());
                    msg.setData(data);
                    msg.what = 1;
                    handler.sendMessage(msg);
                }
            }
            return;
        }
    };

    dataPreload.start();
    return inflater.inflate(R.layout.roles_landing, container, false);
}