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.zbrown.droidsteal.activities.UpdateChecker.java

/**
 * Instantiates the update checker/*from w  ww  . ja  v a  2s.c  om*/
 *
 * @param c            The activity to be used for displaying the messages
 * @param versionUrl   The url of the file containing the version name
 * @param remoteApkUrl The url of the apk
 * @param alertIcon    The icon to show in the dialog, usually the application icon
 */
public UpdateChecker(Activity c, String versionUrl, String remoteApkUrl, int alertIcon) {
    this.activity = c;
    this.context = c.getApplicationContext();
    this.versionUrl = versionUrl;
    this.remoteApkUrl = remoteApkUrl;
    this.alertIcon = alertIcon;
    mHandler = new Handler();
}

From source file:edu.mit.media.funf.configured.ConfiguredPipeline.java

@Override
public void onCreate() {
    super.onCreate();
    handler = new Handler();
    ensureServicesAreRunning();/*w ww .ja v  a  2  s  .  c  om*/
    getConfig().getPrefs().registerOnSharedPreferenceChangeListener(this);
    getSystemPrefs().registerOnSharedPreferenceChangeListener(this);
}

From source file:org.liberty.android.fantastischmemo.downloader.DownloaderAnyMemo.java

@Override
protected void initialRetrieve() {
    dlAdapter = new DownloadListAdapter(this, R.layout.filebrowser_item);
    dlStack = new Stack<ArrayList<DownloadItem>>();
    mHandler = new Handler();
    listView = (ListView) findViewById(R.id.file_list);
    listView.setAdapter(dlAdapter);//from   www .j  av a  2  s  .c  o m
    mProgressDialog = ProgressDialog.show(this, getString(R.string.loading_please_wait),
            getString(R.string.loading_connect_net), true, true, new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    finish();
                }
            });
    new Thread() {
        public void run() {
            try {
                final ArrayList<DownloadItem> list = obtainCategories();
                mHandler.post(new Runnable() {
                    public void run() {
                        dlAdapter.addList(list);
                        sortAdapter();
                        mProgressDialog.dismiss();
                    }
                });

            } catch (final Exception e) {
                mHandler.post(new Runnable() {
                    public void run() {
                        Log.e(TAG, "Error obtaining categories", e);
                        new AlertDialog.Builder(DownloaderAnyMemo.this)
                                .setTitle(getString(R.string.downloader_connection_error))
                                .setMessage(
                                        getString(R.string.downloader_connection_error_message) + e.toString())
                                .setNeutralButton(getString(R.string.back_menu_text),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface arg0, int arg1) {
                                                finish();
                                            }
                                        })
                                .create().show();
                    }
                });
            }
        }
    }.start();
}

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

Handler getClientHandler() {

    return new Handler() {
        @Override/*from w w w.  j  a  va  2 s  .co m*/
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            JSONObject root;
            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);
                }

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

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    settings = this.getActivity().getSharedPreferences("Cyllell", 0);
    try {//  w w  w . j  a  v  a  2s  . 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 (listOfCookbooks.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) {
                    listOfCookbooks.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(ViewCookbooks_Fragment.this.getActivity(),
                            "An error occured during that operation.", Toast.LENGTH_LONG).show();
                    listOfCookbooks.get(tag).SetErrorState();
                }
            }
            CookbookAdapter.notifyDataSetChanged();
        }
    };

    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());
                        Toast.makeText(getActivity(), "This version doesn't support Cookbook editing yet",
                                Toast.LENGTH_SHORT).show();
                        return true;
                    }
                };

                CookbookAdapter = new CookbookListAdaptor(getActivity(), listOfCookbooks, listener,
                        listenerLong);
                try {
                    list = (ListView) getView().findViewById(R.id.cookbooksListView);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (list != null) {
                    if (CookbookAdapter != null) {
                        list.setAdapter(CookbookAdapter);
                    } 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(context).create();
                alertDialog.setTitle("API Error");
                alertDialog.setMessage("There was an error communicating with the API:\n"
                        + msg.getData().getString("exception"));
                alertDialog.setButton2("OK", 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 (listOfCookbooks.size() > 0) {
                handler.sendEmptyMessage(0);
            } else {
                try {
                    handler.sendEmptyMessage(200);
                    Cookbooks = Cut.GetCookbooks();
                    handler.sendEmptyMessage(201);
                    JSONArray Keys = Cookbooks.names();
                    String URI = "";
                    String Version = "0.0.0";
                    JSONObject cookbook;
                    for (int i = 0; i < Cookbooks.length(); i++) {
                        cookbook = new JSONObject(Cookbooks.getString(Keys.get(i).toString()));
                        //URI = Cookbooks.getString(Keys.get(i).toString()).replaceFirst("^(https://|http://).*/cookbooks/", "");
                        //Version = Cookbooks.getString(Keys.get(i).toString())
                        //Log.i("Cookbook Name", Keys.get(i).toString());
                        URI = cookbook.getString("url").replaceFirst("^(https://|http://).*/cookbooks/", "");
                        //Log.i("Cookbook URL", URI);

                        JSONArray versions = cookbook.getJSONArray("versions");

                        Version = versions.getJSONObject(versions.length() - 1).getString("version");
                        //Log.i("Cookbook version", Version);

                        listOfCookbooks.add(new Cookbook(Keys.get(i).toString(), URI, Version));
                    }

                    handler.sendEmptyMessage(202);
                    handler.sendEmptyMessage(0);
                } catch (Exception e) {
                    BugSenseHandler.log("ViewCookbooksFragment", e);
                    e.printStackTrace();
                    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.cookbooks_landing, container, false);
}

From source file:com.jakebasile.android.linkshrink.ShortenUrl.java

private void shorten(SharedPreferences prefs, String longUrl) {
    // guard against bad input.
    if (longUrl == null || longUrl.length() == 0) {
        showBadInputToast();/* w w  w .j a  va2s .c  o  m*/
        return;
    }
    final String service = prefs.getString("service", GOOGL);
    String host = Uri.parse(longUrl).getHost();
    if (host == null || host.length() == 0) {
        showBadInputToast();
        return;
    }
    if (host.endsWith(service)) {
        onUrlAlreadyShortened(longUrl);
        finish();
        return;
    }
    _handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0: {
                if (_shortUrl != null) {
                    onUrlShortened(_shortUrl);
                } else {
                    String display = String.format(getResources().getString(R.string.unknownerror), service);
                    Toast.makeText(getApplicationContext(), display, Toast.LENGTH_LONG).show();
                }
                break;
            }
            case 1: {
                String display = String.format(getResources().getString(R.string.commerror), service);
                Toast.makeText(getApplicationContext(), display, Toast.LENGTH_LONG).show();
                break;
            }
            case 2: {
                String display = String.format(getResources().getString(R.string.urlerror), service);
                Toast.makeText(getApplicationContext(), display, Toast.LENGTH_LONG).show();
                break;
            }
            }
            finish();
            return;
        }
    };
    if (service.equalsIgnoreCase(ISGD)) {
        shortenWithIsgd(longUrl);
    } else if (service.equalsIgnoreCase(BITLY)) {
        shortenWithBitly(longUrl, prefs);
    } else if (service.equalsIgnoreCase(GOOGL)) {
        shortenWithGoogl(longUrl);
    } else {
        Toast.makeText(getApplicationContext(), R.string.badconfig, Toast.LENGTH_LONG).show();
        finish();
    }
}

From source file:org.openremote.android.console.model.PollingHelper.java

/**
 * Instantiates a new polling helper.//w w w .  ja  v a 2 s.c  om
 * 
 * @param ids the ids
 * @param context the context
 */
public PollingHelper(HashSet<Integer> ids, final Context context) {
    this.context = context;
    this.serverUrl = AppSettingsModel.getSecuredServer(context);
    readDeviceId(context);

    Iterator<Integer> id = ids.iterator();
    if (id.hasNext()) {
        pollingStatusIds = id.next().toString();
    }
    while (id.hasNext()) {
        pollingStatusIds = pollingStatusIds + "," + id.next();
    }

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            isPolling = false;
            Log.i(LOG_CATEGORY, "polling failed and canceled." + msg.what);
            // only if the network is error, server error and request error, 
            // switch controller server, or endless loop would happen to switch server.
            int statusCode = msg.what;
            if (statusCode == NETWORK_ERROR || statusCode == ControllerException.SERVER_ERROR
                    || statusCode == ControllerException.REQUEST_ERROR) {
                ORControllerServerSwitcher.doSwitch(context);
            } else {
                ViewHelper.showAlertViewWithTitle(context, "Polling Error",
                        ControllerException.exceptionMessageOfCode(statusCode));
            }
        }
    };
}

From source file:com.app.jdy.widget.CustomSaveMoneyDialog.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.savemoney_dialog);
    listView = (ListView) findViewById(R.id.savemoney_listView);
    promoCodeTextView = (TextView) findViewById(R.id.PromoCode);
    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override//  ww  w.ja v a2  s.  com
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            addressTextView = (TextView) arg1.findViewById(R.id.address);
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + addressTextView.getText()));
            context.startActivity(intent);
        }
    });
    new Thread(ManagerRunnable).start();
    mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {// ui?
            switch (msg.what) {
            case 2:
                customManagerAdapter = new CustomManagerAdapter(context, listViewProductManagerList);
                listView.setAdapter(customManagerAdapter);

                break;
            case 3:
                promoCodeTextView.setText(coupon);
                break;
            default:
                break;
            }
        }
    };
}

From source file:com.nextgis.firereporter.ScanexSubscriptionItem.java

protected void Prepare(GetFiresService c) {
    this.c = c;//from  w  w w . ja  va 2  s .  c o m
    nID = -1;
    bHasNews = false;

    mFillDataHandler = new Handler() {
        public void handleMessage(Message msg) {

            Bundle resultData = msg.getData();
            boolean bHaveErr = resultData.getBoolean(GetFiresService.ERROR);
            if (bHaveErr) {
                SendError(resultData.getString(GetFiresService.ERR_MSG));
            } else {
                int nType = resultData.getInt(GetFiresService.SOURCE);
                String sData = resultData.getString(GetFiresService.JSON);
                switch (nType) {
                case 5:
                    FillData(nType, sData);
                    break;
                default:
                    break;
                }
            }
        };
    };

    mmoItems = new HashMap<Long, ScanexNotificationItem>();
}

From source file:com.klinker.android.spotify.fragment.BaseOAuthFragment.java

/**
 * Process information encoded in URL once a page has finished loading to see if we are done
 *//* ww  w.  ja v a  2  s  . c o m*/
protected boolean processPageFinished(String url, boolean authComplete) {
    if (url.contains("?code=") && !authComplete) {
        Uri uri = Uri.parse(url);
        String authCode = uri.getQueryParameter("code");
        Log.v(TAG, "auth code: " + authCode);
        getTokenAsyncTask(authCode).execute();
        authComplete = true;
    } else if (url.contains("error=access_denied")) {
        Log.v(TAG, "ACCESS_DENIED_HERE");
        Toast.makeText(getActivity(), getString(R.string.auth_failed), Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getActivity().finish();
            }
        }, 500);
        authComplete = true;
    }

    return authComplete;
}