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.arquitetaweb.restaurantes.fragment.CardapioFragment.java

private void carregarDadosJson(final View view) {

    handler = new Handler();

    progressDialog = new ProgressDialog(contexto);
    progressDialog.setCancelable(false);
    progressDialog.setMessage("atualizando mapa das mesas...");
    progressDialog.show();//from w ww  .ja  v a2  s . co  m

    Thread thread = new Thread() {
        public void run() {
            if (Utils.isConnected(contexto)) {
                String url = Utils.getUrlServico(contexto) + "/Api/SituacaoMesas";
                JSONParser jParser = new JSONParser();
                json = jParser.getJSONFromUrl(url);

                contexto.runOnUiThread(new Runnable() {
                    public void run() {
                        ArrayList<HashMap<String, String>> mesasLista = new ArrayList<HashMap<String, String>>();
                        for (int i = 0; i < json.length(); i++) {
                            try {
                                JSONObject c = json.getJSONObject(i);

                                HashMap<String, String> map = new HashMap<String, String>();

                                map.put(KEY_ID, c.getString(KEY_ID));
                                map.put(KEY_NUMEROMESA, c.getString(KEY_NUMEROMESA));
                                map.put(KEY_CODIGOEXTERNO, c.getString(KEY_CODIGOEXTERNO));
                                map.put(KEY_SITUACAO, c.getString(KEY_SITUACAO));

                                mesasLista.add(map);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        mesas = (GridView) view.findViewById(R.id.list);
                        adapter = new MesaAdapter(contexto, mesasLista);
                        mesas.setAdapter(adapter);

                        // Click event for single list row
                        mesas.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                TextView idItem = (TextView) view.findViewById(R.id.idItem);

                                Bundle bun = new Bundle();
                                bun.putString("id", (String) idItem.getText());

                                abrirDetalhes(view, bun);
                            }

                            private void abrirDetalhes(View view, Bundle bun) {
                                Intent intent = new Intent(view.getContext(), DetailsActivity.class);
                                intent.putExtras(bun);
                                startActivityForResult(intent, 100);
                            }
                        });
                        progressDialog.dismiss();
                    }
                });

            } else {
                contexto.runOnUiThread(new Runnable() {
                    public void run() {
                        progressDialog.dismiss();
                        new Alerta(contexto, "", "No Foi Localizado o Servidor!" + "\nCausas:"
                                + "\nConexo OK?" + "\nServidor correto?");
                        //                          Toast.makeText(contexto, "No Foi Localizado o Servidor!",
                        //                            Toast.LENGTH_LONG).show();                          
                        //Intent intent = new Intent("settings://sandbox");
                        //startActivity(intent);
                    }
                });
            }
        }
    };
    thread.start();
}

From source file:com.fastbootmobile.twofactorauthdemo.MainActivity.java

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

    setContentView(R.layout.info_layout);

    Button regButton = (Button) findViewById(R.id.register);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        if (extras.getString("otp", null) != null) {
            TextView txt = (TextView) findViewById(R.id.txt);
            regButton.setVisibility(View.GONE);
            txt.setText("One Time Password :  " + extras.getString("otp", null));
            return;
        }//from ww  w.  j av  a 2 s. co  m
    }

    mReg = new OwnPushRegistrant(this);
    mHandler = new Handler();
    receiver = new RegisterReceiver(new Handler());

    IntentFilter filter = new IntentFilter(OwnPushClient.INTENT_REGISTER);
    filter.addCategory(BuildConfig.APP_PUBLIC_KEY);

    registerReceiver(receiver, filter);

    final SharedPreferences prefs = this.getApplicationContext().getSharedPreferences(OwnPushClient.PREF_PUSH,
            Context.MODE_PRIVATE);

    if (!prefs.getBoolean(OwnPushClient.PREF_REG_DONE, false)) {

        regButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OwnPushCrypto fp = new OwnPushCrypto();
                OwnPushCrypto.AppKeyPair keys = fp.generateInstallKey();

                boolean ret = mReg.register(BuildConfig.APP_PUBLIC_KEY, keys.getPublicKey());

                if (ret) {
                    //STORE THEM
                    prefs.edit().putString(OwnPushClient.PREF_PUBLIC_KEY, keys.getPublicKey()).commit();
                    prefs.edit().putString(OwnPushClient.PREF_PRIVATE_KEY, keys.getPrivateKey()).commit();
                }
            }
        });
    } else {
        regButton.setVisibility(View.GONE);

        updateUI();

        if (prefs.getString("device_uid", null) == null) {
            registerWithBackend();
        }
    }

}

From source file:com.liato.bankdroid.WebViewActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);// ww w  .j  a  va  2 s  . c  o  m
    this.addTitleButton(R.drawable.title_icon_back, "back", this);
    this.addTitleButton(R.drawable.title_icon_forward, "forward", this);
    this.addTitleButton(R.drawable.title_icon_refresh, "refresh", this);
    this.setTitleButtonEnabled("forward", false);
    this.setTitleButtonEnabled("back", false);
    this.setTitleButtonEnabled("refresh", false);

    final CookieSyncManager csm = CookieSyncManager.createInstance(this);
    mWebView = (WebView) findViewById(R.id.wvBank);
    mWebView.setBackgroundColor(0);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setUserAgentString(Urllib.DEFAULT_USER_AGENT);
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgressBar(progress);
            if (progress == 100) {
                Handler handler = new Handler();
                Runnable runnable = new Runnable() {
                    public void run() {
                        activity.hideProgressBar();
                    }
                };
                // Let the progress bar hit 100% before we hide it.
                handler.postDelayed(runnable, 100);

            } else if (mFirstPageLoaded) {
                activity.showProgressBar();
            }
        }
    });
    mWebView.setWebViewClient(new BankWebViewClient());
    String preloader = "Error...";
    try {
        preloader = IOUtils.toString(getResources().openRawResource(R.raw.loading));
        preloader = String.format(preloader, "", // Javascript function
                "" // HTML
        );
    } catch (NotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mWebView.loadDataWithBaseURL("what://is/this/i/dont/even", preloader, "text/html", "utf-8", null);

    Bundle extras = getIntent().getExtras();
    final long bankId = extras.getLong("bankid", -1);
    //final long bankId = -1;
    if (bankId >= 0) {
        Runnable generateLoginPage = new Runnable() {
            public void run() {
                Bank bank = BankFactory.bankFromDb(bankId, WebViewActivity.this, false);
                SessionPackage loginPackage = bank.getSessionPackage(WebViewActivity.this);
                CookieStore cookieStore = loginPackage.getCookiestore();
                if ((cookieStore != null) && !cookieStore.getCookies().isEmpty()) {
                    CookieManager cookieManager = CookieManager.getInstance();
                    String cookieString;
                    for (Cookie cookie : cookieStore.getCookies()) {
                        cookieString = String.format("%s=%s;%spath=%s; domain=%s;", cookie.getName(),
                                cookie.getValue(),
                                cookie.getExpiryDate() == null ? ""
                                        : "expires=" + cookie.getExpiryDate() + "; ",
                                cookie.getPath() == null ? "/" : cookie.getPath(), cookie.getDomain());
                        cookieManager.setCookie(cookie.getDomain(), cookieString);
                    }
                    csm.sync();
                }
                mWebView.loadDataWithBaseURL("what://is/this/i/dont/even", loginPackage.getHtml(), "text/html",
                        "utf-8", null);
            }
        };
        new Thread(generateLoginPage).start();
    }
}

From source file:to.sven.androidrccar.arduino.test.AccessoryTestSuiteRunner.java

/**
 * Runs the {@link TestSuite}.//from   w  ww  .  ja  v a 2 s  .  c  o  m
 * @param inputStream
 * @param outputStream
 * @param listener
 */
public synchronized void runTests(FileInputStream inputStream, FileOutputStream outputStream,
        AccessoryTestSuiteRunnerListener listener) {
    if (handler == null) {
        this.inputStream = inputStream;
        this.outputStream = outputStream;
        handler = new Handler();
        this.listener = listener;
        new Thread(this).start();
    }
}

From source file:com.android.talkback.labeling.CustomLabelMigrationManager.java

public CustomLabelMigrationManager(Context context) {
    mExecutor = Executors.newSingleThreadExecutor();
    mHandler = new Handler();
    TalkBackService service = TalkBackService.getInstance();
    if (service != null) {
        mManager = service.getLabelManager();
    } else {/* w  w w . java 2 s  .  c  o  m*/
        mManager = new CustomLabelManager(context);
    }
    mContext = context;
}

From source file:com.temboo.example.YouTubeResultView.java

/**
 * A utility method to retrieve the thumbnail image on a separate thread, and populate
 * the image view with that thumbnail//from ww  w.j  av a 2s  .c o m
 * @param urlString - the URL of the thumbnail to retrieve
 * @param imageView - the view to populate with the thumbnail
 */
private void fetchDrawableOnThread(final String urlString, final ImageView imageView) {

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

    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet request = new HttpGet(urlString);
                HttpResponse response = httpClient.execute(request);
                InputStream is = response.getEntity().getContent();
                Drawable drawable = Drawable.createFromStream(is, "src");

                Message message = handler.obtainMessage(1, drawable);
                handler.sendMessage(message);
            } catch (Exception e) {
                Toast.makeText(getContext(), "An error occurred retrieving the video thumbnail",
                        Toast.LENGTH_LONG).show();
            }
        }
    };
    thread.start();
}

From source file:net.networksaremadeofstring.pulsant.portal.ColoLanding.java

public void onCreate(Bundle savedInstanceState) {
    API.SessionID = getIntent().getStringExtra("sessionid");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cololanding);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("Colocation");

    detailsdialog = new Dialog(this);

    EditHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Toast.makeText(ColoLanding.this, "Description updated successfully!", Toast.LENGTH_SHORT)
                        .show();/*  w  ww . j  a  v  a 2 s  .  c o m*/
            } else {
                Toast.makeText(ColoLanding.this, "There was an error updating that description",
                        Toast.LENGTH_SHORT).show();
            }
        }
    };

    //Temp
    list = (ListView) findViewById(R.id.ColoCabList);
    final ProgressDialog dialog = ProgressDialog.show(this, "Pulsant Portal", "Please wait: loading data....",
            true);
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();
            if (Success.equals("true")) {
                UpdateErrorMessage(ErrorMessage);
                adapter = new ColoRacksAdaptor(ColoLanding.this, listOfColoRacks);
                list.setAdapter(adapter);
                list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            } else {
                UpdateErrorMessage(ErrorMessage);
            }
        }
    };

    Thread dataPreload = new Thread() {
        public void run() {
            try {
                Colo = API.PortalQuery("colocation", "none");
                Success = Colo.getString("success");
            } catch (JSONException e) {
                ErrorMessage = "An unrecoverable JSON Exception occurred.";
                //UpdateErrorMessage("An unrecoverable JSON Exception occurred.");
            }

            if (Success.equals("false")) {
                try {
                    //UpdateErrorMessage(Colo.getString("msg"));
                    ErrorMessage = Colo.getString("msg");
                } catch (JSONException e) {
                    ErrorMessage = "An unrecoverable JSON Exception occured.";
                    //UpdateErrorMessage("An unrecoverable JSON Exception occured.");
                }
            } else {
                Log.i("APIFuncs", Colo.toString());
                try {
                    ColoCabs = Colo.getJSONArray("colocation");
                    ErrorMessage = "";
                    //UpdateErrorMessage("");
                } catch (JSONException e) {
                    ErrorMessage = "There are no Co-Location Cabinets in your account.";
                    //UpdateErrorMessage("There are no Co-Location Cabinets in your account.");
                }

                int ColoCount = ColoCabs.length();

                if (ColoCount == 0) {
                    //UpdateErrorMessage("There are no colocation cabinets for your account.");
                    ErrorMessage = "There are no colocation cabinets for your account.";
                    handler.sendEmptyMessage(0);
                    return;
                }

                for (int i = 0; i < ColoCount; i++) {
                    JSONObject CurrentColo = null;
                    try {
                        CurrentColo = ColoCabs.getJSONObject(i);
                    } catch (JSONException e1) {
                        Log.e("APIFuncs", e1.getMessage());
                    }

                    try {
                        listOfColoRacks.add(new ColoRacks(CurrentColo.getString("ip"),
                                CurrentColo.getString("servercode"), CurrentColo.getString("facility"),
                                CurrentColo.getInt("bandwidth"), CurrentColo.getString("bandwidthTotal"),
                                CurrentColo.getInt("transferlimit"), CurrentColo.getString("state"),
                                CurrentColo.getString("description")));
                    } catch (JSONException e) {
                        Log.e("APIFuncs", e.getMessage());
                    }
                }
            }
            handler.sendEmptyMessage(0);
        }
    };

    dataPreload.start();
}

From source file:me.unsharable.activities.Hackbook.java

/** Called when the activity is first created. */
@Override//from   w w w.ja  va  2 s .  co m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
        Util.showAlert(this, "Warning",
                "Facebook Applicaton ID must be " + "specified before running this example: see FbAPIs.java");
        return;
    }

    setContentView(R.layout.facebook_login);
    mHandler = new Handler();

    mText = (TextView) Hackbook.this.findViewById(R.id.txt);
    mUserPic = (ImageView) Hackbook.this.findViewById(R.id.user_pic);

    // Create the Facebook Object using the app id.
    Utility.mFacebook = new Facebook(APP_ID);
    // Instantiate the asynrunner object for asynchronous api calls.
    Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);

    mLoginButton = (LoginButton) findViewById(R.id.login);

    // restore session if one exists
    SessionStore.restore(Utility.mFacebook, this);
    SessionEvents.addAuthListener(new FbAPIsAuthListener());
    SessionEvents.addLogoutListener(new FbAPIsLogoutListener());

    /*
     * Source Tag: login_tag
     */
    mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);

    if (Utility.mFacebook.isSessionValid()) {
        requestUserData();
    }
    /*
      list = (ListView) findViewById(R.id.main_list);
            
      list.setOnItemClickListener(this);
      list.setAdapter(new ArrayAdapter<String>(this, R.layout.main_list_item, main_items));
     */

}

From source file:com.BeatYourRecord.AssignmentSyncService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    final int startId_ = startId;
    if (!isRunning) {
        isRunning = true;//from   w ww.  j av  a 2 s. co  m
    } else {
        Log.d(LOG_TAG, "sync service is already running, stop and return!!!");
        // For whatever reason, the previous onStartCommand is still running,
        // perhaps the service got
        // killed by runtime and this service is not STICKY, so it never reach end
        // to call stopSelf?
        // So just kill it and let another alarm to start it again.
        stopSelf(startId_);
        return Service.START_NOT_STICKY;
    }

    // Log.d(LOG_TAG, "incoming startId=" + startId_);
    // Log.d(LOG_TAG, "thread id=" + Thread.currentThread().getId());
    // Log.d(LOG_TAG, "thread count=" +
    // Thread.currentThread().getThreadGroup().activeCount());
    if ((flags & Service.START_FLAG_RETRY) == Service.START_FLAG_RETRY) {
        Log.d(LOG_TAG, "assignment service retry");
    }

    ytdDomain = intent.getStringExtra(DbHelper.YTD_DOMAIN);
    ytdJsonRpcUrl = "http://" + ytdDomain + "/jsonrpc";

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            stopSelf(startId_);
            Log.d(LOG_TAG, "startId=" + startId_ + " is finished.");
        }
    };

    new Thread() {
        @Override
        public void run() {
            String newAssignmentId = updateAssignmentDb();
            if (newAssignmentId != null) {
                Intent intent = new Intent();
                intent.setAction(MainActivity.NEW_ASSIGNMENT_UPDATE);
                intent.putExtra(DbHelper.YTD_DOMAIN, ytdDomain);
                intent.putExtra(DbHelper.ASSIGNMENT_ID, newAssignmentId);
                sendBroadcast(intent);
                sendNotification(ytdDomain, newAssignmentId);
            }

            handler.sendEmptyMessage(0);
        }
    }.start();

    return Service.START_NOT_STICKY;
}

From source file:com.facebook.android.Hackbook.java

/** Called when the activity is first created. */
@Override//www  .j av  a2s  . c  o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (APP_ID == null) {
        Util.showAlert(this, "Warning",
                "Facebook Applicaton ID must be " + "specified before running this example: see FbAPIs.java");
        return;
    }

    setContentView(R.layout.main);
    mHandler = new Handler();

    mText = (TextView) Hackbook.this.findViewById(R.id.txt);
    mUserPic = (ImageView) Hackbook.this.findViewById(R.id.user_pic);

    // Create the Facebook Object using the app id.
    Utility.mFacebook = new Facebook(APP_ID);
    // Instantiate the asynrunner object for asynchronous api calls.
    Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);

    mLoginButton = (LoginButton) findViewById(R.id.login);

    // restore session if one exists
    SessionStore.restore(Utility.mFacebook, this);
    SessionEvents.addAuthListener(new FbAPIsAuthListener());
    SessionEvents.addLogoutListener(new FbAPIsLogoutListener());

    /*
     * Source Tag: login_tag
     */
    mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);

    if (Utility.mFacebook.isSessionValid()) {
        requestUserData();
    }

    list = (ListView) findViewById(R.id.main_list);

    list.setOnItemClickListener(this);
    list.setAdapter(new ArrayAdapter<String>(this, R.layout.main_list_item, main_items));
}