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.skalski.raspberrycontrol.Activity_TempSensors.java

Handler getClientHandler() {

    return new Handler() {
        @Override//from   ww  w  . j av a2 s .co m
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            JSONObject root;
            JSONArray tempsensors;
            tempsensorsArray = new ArrayList<Custom_TempSensorsAdapter>();
            tempsensorsLayout.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);
                    toast_connection_error(err);

                } else {

                    tempsensors = root.getJSONArray(TAG_TEMPSENSORS);

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

                        JSONObject tempsensor = tempsensors.getJSONObject(i);

                        String type = tempsensor.getString(TAG_TYPE);
                        String id = tempsensor.getString(TAG_ID);
                        String crc = tempsensor.getString(TAG_CRC);

                        float temp = (float) tempsensor.getDouble(TAG_TEMP);
                        String tempstr = String.format("%.3f", temp);

                        if (tempstr != null)
                            tempstr = tempstr + " \u2103";

                        tempsensorsArray.add(new Custom_TempSensorsAdapter(type, id, tempstr, crc));
                    }

                    if (tempsensors.length() == 0) {
                        Log.w(LOGTAG, LOGPREFIX + "can't find 1-wire temperature sensors");
                        toast_connection_error(getResources().getString(R.string.error_msg_7));
                    }
                }

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

            setListAdapter(new Custom_TempSensorsArrayAdapter(getApplicationContext(), tempsensorsArray));
        }
    };
}

From source file:com.baidu.asynchttpclient.AsyncHttpResponseHandler.java

/**
 * Creates a new AsyncHttpResponseHandler
 *///  w  w w.j a  v  a  2  s  .  c o m
public AsyncHttpResponseHandler() {
    // Set up a handler to post events back to the correct thread if possible
    if (Looper.myLooper() != null) {
        handler = new Handler() {
            public void handleMessage(Message msg) {
                AsyncHttpResponseHandler.this.handleMessage(msg);
            }
        };
    }
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    list = (ListView) this.getActivity().findViewById(R.id.environmentsListView);
    settings = this.getActivity().getSharedPreferences("Cyllell", 0);
    try {//from  w  w  w .  jav  a2 s. c om
        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 (listOfEnvironments.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) {
                    listOfEnvironments.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(ViewEnvironments_Fragment.this.getActivity(),
                            "An error occured during that operation.", Toast.LENGTH_LONG).show();
                    listOfEnvironments.get(tag).SetErrorState();
                }
            }
            EnvironmentAdapter.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) {
                        //Log.i("OnClick","Clicked");
                        GetMoreDetails((Integer) v.getTag());
                    }
                };

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

                EnvironmentAdapter = new EnvironmentListAdaptor(getActivity().getBaseContext(),
                        listOfEnvironments, listener, listenerLong);
                list = (ListView) getView().findViewById(R.id.environmentsListView);
                if (list != null) {
                    if (EnvironmentAdapter != null) {
                        list.setAdapter(EnvironmentAdapter);
                    } else {
                        //Log.e("EnvironmentAdapter","EnvironmentAdapter 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 (listOfEnvironments.size() > 0) {
                handler.sendEmptyMessage(0);
            } else {
                try {
                    handler.sendEmptyMessage(200);
                    Environments = Cut.GetEnvironments();
                    handler.sendEmptyMessage(201);

                    JSONArray Keys = Environments.names();

                    for (int i = 0; i < Keys.length(); i++) {
                        listOfEnvironments.add(
                                new Environment(Keys.getString(i), Environments.getString(Keys.getString(i))
                                        .replaceFirst("^(https://|http://).*/environments/", "")));
                    }

                    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.environments_landing, container, false);
}

From source file:com.nhn.android.archetype.base.AABaseApplicationOrg.java

public static void applicationAllKill() {
    final ActivityManager am = (ActivityManager) _internalInstance.getSystemService(Activity.ACTIVITY_SERVICE);
    // stop running service inside current process.
    List<RunningServiceInfo> serviceList = am.getRunningServices(100);
    for (RunningServiceInfo service : serviceList) {
        if (service.pid == android.os.Process.myPid()) {
            Intent stop = new Intent();
            stop.setComponent(service.service);
            _internalInstance.stopService(stop);
        }//w w  w. ja  va  2  s .co m
    }

    // move current task to background.
    Intent launchHome = new Intent(Intent.ACTION_MAIN);
    launchHome.addCategory(Intent.CATEGORY_DEFAULT);
    launchHome.addCategory(Intent.CATEGORY_HOME);
    _internalInstance.startActivity(launchHome);

    // post delay runnable(waiting for home application launching)
    new Handler().postDelayed(new Runnable() {
        public void run() {
            am.killBackgroundProcesses(_internalInstance.getPackageName());
        }
    }, 2000);
}

From source file:net.bible.android.view.activity.StartupActivity.java

/** Called when the activity is first created. */
@Override//from   w w  w  .ja va2s  .co  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.startup_view);

    // do not show an actionBar/title on the splash screen
    getSupportActionBar().hide();

    TextView versionTextView = (TextView) findViewById(R.id.versionText);
    String versionMsg = BibleApplication.getApplication().getString(R.string.version_text,
            CommonUtils.getApplicationVersionName());
    versionTextView.setText(versionMsg);

    //See if any errors occurred during app initialisation, especially upgrade tasks
    int abortErrorMsgId = BibleApplication.getApplication().getErrorDuringStartup();

    // check for SD card 
    // it would be great to check in the Application but how to show dialog from Application?
    if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        abortErrorMsgId = R.string.no_sdcard_error;
    }

    // show fatal startup msg and close app
    if (abortErrorMsgId != 0) {
        Dialogs.getInstance().showErrorMsg(abortErrorMsgId, new Callback() {
            @Override
            public void okay() {
                // this causes the blue splashscreen activity to finish and since it is the top the app closes
                finish();
            }
        });
        // this aborts further initialisation but leaves blue splashscreen activity
        return;
    }

    // allow call back and continuation in the ui thread after JSword has been initialised
    final Handler uiHandler = new Handler();
    final Runnable uiThreadRunnable = new Runnable() {
        @Override
        public void run() {
            postBasicInitialisationControl();
        }
    };

    // initialise JSword in another thread (takes a long time) then call main ui thread Handler to continue
    // this allows the splash screen to be displayed and an hourglass to run
    new Thread() {
        public void run() {
            try {
                // allow the splash screen to be displayed immediately
                CommonUtils.pauseMillis(1);

                // force Sword to initialise itself
                Initialisation.getInstance().initialiseNow();
            } finally {
                // switch back to ui thread to continue
                uiHandler.post(uiThreadRunnable);
            }
        }
    }.start();
}

From source file:com.hybris.mobile.Hybris.java

/**
 * Method to activate the geofencing monitoring
 *//*from w ww.  ja  v  a2  s . c o m*/
public static void enableGeofencing() {
    // TODO - handle the success/error coming within the handler
    Handler handler = new Handler();

    if (isGooglePlayServicesConnected()) {
        // Enable geofence capabilities
        if (isGeofencingActivated()) {
            GeofenceUtils.enableGeofencesMonitoring(GeofenceJsonSharedPreferences.createGeofencable(
                    Hybris.getAppContext(), DataConstants.PREFIX_GEOFENCE_SHARED_PREFERENCES), handler, 1, 2);
        }
        // Disable geofence capabilities
        else {
            GeofenceUtils.disableGeofencesMonitoring(GeofenceJsonSharedPreferences.createGeofencable(
                    Hybris.getAppContext(), DataConstants.PREFIX_GEOFENCE_SHARED_PREFERENCES), handler, 1, 2);
        }
    } else {
        Toast.makeText(Hybris.getAppContext(), R.string.error_geofence_lib_not_available, 40000);
    }

}

From source file:fi.hut.soberit.accelerometer.AccelerometerAxisUploader.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;
    }//from w w w.  j av  a 2 s. c  om

    handler = new Handler();

    final StringBuilder builder = new StringBuilder();

    builder.append(intent.getStringExtra(INTENT_AHL_URL));
    builder.append("?");
    builder.append("username=");
    builder.append(intent.getStringExtra(INTENT_USERNAME));
    builder.append("&");
    builder.append("password=");
    builder.append(intent.getStringExtra(INTENT_PASSWORD));
    builder.append("&");
    builder.append("weblet=");
    builder.append(intent.getStringExtra(INTENT_WEBLET));

    baseUrl = builder.toString();

    Log.d(TAG, baseUrl);

    handler.postDelayed(updater, UploadRecords.UPLOAD_FREQUENCY);

    return res;
}

From source file:ua.at.tsvetkov.data_processor.ProcessingCentre.java

/**
 * @param request/*from w  w  w .j  av a2s.c  o m*/
 * @param clazz
 */
public ProcessingCentre(Request request, Class<T> clazz) {
    if (request == null || clazz == null) {
        throw new InvalidParameterException(INVALID_PARAMETER);
    }
    this.request = request;
    this.clazz = clazz;
    this.callback = null;

    if (Looper.myLooper() != null)
        handler = new Handler();
    else
        handler = null;
    thread = Thread.currentThread();
}

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

Handler getClientHandler() {

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

            JSONObject root;
            JSONArray processes;
            processesArray = new ArrayList<Custom_ProcessAdapter>();
            processesLayout.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 {

                    processes = root.getJSONArray(TAG_PROCESSES);

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

                        JSONObject process = processes.getJSONObject(i);

                        String name = process.getString(TAG_NAME);
                        String user = process.getString(TAG_USER);
                        String state = process.getString(TAG_STATE);

                        int pid = process.getInt(TAG_PID);
                        String pidstr = Integer.toString(pid);

                        if (state != null)
                            state = state.substring(0, 1);

                        processesArray.add(new Custom_ProcessAdapter(name, pidstr, user, state));
                    }

                    if (processes.length() == 0) {
                        Log.e(LOGTAG, LOGPREFIX + "list of processes is empty - please report a bug");
                        toast_connection_error(getResources().getString(R.string.error_msg_9));
                    }
                }

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

            setListAdapter(new Custom_ProcessesArrayAdapter(getApplicationContext(), processesArray));
        }
    };
}

From source file:com.corebase.android.framework.http.client.AsyncHttpResponseHandler.java

/**
 * Creates a new AsyncHttpResponseHandler
 *//*from  w w  w . ja va2 s.c om*/
public AsyncHttpResponseHandler() {
    // Set up a handler to post events back to the correct thread if
    // possible
    if (Looper.myLooper() != null) {
        handler = new Handler() {
            public void handleMessage(Message msg) {
                AsyncHttpResponseHandler.this.handleMessage(msg);
            }
        };
    }
}