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:li.klass.fhem.fragments.SendCommandFragment.java

private void sendCommandIntent(String command) {
    final Context context = getActivity();
    Intent intent = new Intent(Actions.EXECUTE_COMMAND);
    intent.setClass(getActivity(), SendCommandIntentService.class);
    intent.putExtra(BundleExtraKeys.COMMAND, command);
    intent.putExtra(BundleExtraKeys.RESULT_RECEIVER, new ResultReceiver(new Handler()) {
        @Override//from www  . j a v a2s . c  o  m
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            if (resultData != null && resultCode == ResultCodes.SUCCESS
                    && resultData.containsKey(BundleExtraKeys.COMMAND_RESULT)) {
                String result = resultData.getString(BundleExtraKeys.COMMAND_RESULT);
                if (result == null || result.equals("")) {
                    update(false);
                    return;
                }

                if (isEmpty(result.replaceAll("[\\r\\n]", "")))
                    return;
                new AlertDialog.Builder(context).setTitle(R.string.command_execution_result).setMessage(result)
                        .setPositiveButton(R.string.okButton, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.cancel();
                                update(false);
                            }
                        }).show();
            }
        }
    });
    getActivity().startService(intent);
}

From source file:com.bellman.bible.android.view.activity.StartupActivity.java

/**
 * Called when the activity is first created.
 *//*from w w  w  .j  a  v a 2s.com*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //        setContentView(R.layout.startup_view);

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

    //get the linear layout
    //        pHolder = (LinearLayout) findViewById(R.id.progress_holder);

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

    //See if any errors occurred during app initialisation, especially upgrade tasks
    // TODO: 8/15/2016 Remember changes made here
    int abortErrorMsgId = 0;//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.google.appinventor.components.runtime.MediaStore.java

/**
 * Creates a new MediaStore component./*w  ww  .  j av a 2 s  .  c o  m*/
 *
 * @param container the Form that this component is contained in.
 */
public MediaStore(ComponentContainer container) {
    super(container.$form());
    componentContainer = container;
    androidUIHandler = new Handler();
    serviceURL = "http://ai-mediaservice.appspot.com";
}

From source file:com.sanjaydalvi.spacestationlocator.MainActivity.java

@Override
public void onMapReady(GoogleMap map) {

    // clear previous marker
    map.clear();// ww w. ja v a  2 s  .c o m
    // Move the camera instantly to hamburg with a zoom of 5
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 3));
    // Zoom in, animating the camera.
    map.animateCamera(CameraUpdateFactory.zoomTo(3), 2000, null);
    // add space ship marker on map
    map.addMarker(new MarkerOptions().position(currentLocation)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.spaceship2)));
    map.setOnMarkerClickListener(new OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker arg0) {
            // on marker click, call showLocationToast to display location
            showLocation();

            if (recursiveLocate == false) {
                // if show recursive location false, start showing location in intervals
                recursiveLocate = true;
                counterHandler = new Handler();
                counterHandler.postDelayed(locationChanger, recursiveCheck_Interval);
                Snackbar.make(getWindow().getDecorView().getRootView(), "Automatic Update : Started",
                        Snackbar.LENGTH_LONG).setAction("Action", null).show();
            } else {
                // else stop looking up for location
                recursiveLocate = false;
                counterHandler.removeCallbacksAndMessages(null);
                Snackbar.make(getWindow().getDecorView().getRootView(), "Automatic Update : Stopped",
                        Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }

            return true;
        }
    });
}

From source file:com.morphoss.jumble.frontend.CategoryScreenActivity.java

@Override
protected void onResume() {
    super.onResume();
    myApp.resumeMusic();//from w  w w  .j a v  a2 s.co m
    if (!Category.unlockedCategories.isEmpty()) {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;
        int width = displaymetrics.widthPixels;
        pga = new CategoryGridAdapter(this, width, height);
        new LoadCategoryTask().execute();
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Show the popup window of an unlocked level after 0.5s =
                // 500ms
                if (!Category.unlockedCategories.isEmpty()) {
                    PopupWindowLevel();
                }

            }
        }, 500);
    }
}

From source file:com.wilson.android.library.DrawableManager.java

public void fetchDrawableOnThreadForListener(final String urlString, final DrawableManagerListener artItem) {
    if (drawableMap.containsKey(urlString)) {
        artItem.setFetchedDrawable(drawableMap.get(urlString));
    }//from  ww w .  ja va 2s .c  o m

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

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

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderFE.java

@Override
protected void initialRetrieve() {
    mHandler = new Handler();
    dlAdapter = new DownloadListAdapter(this, R.layout.filebrowser_item);
    listView = (ListView) findViewById(R.id.file_list);
    listView.setAdapter(dlAdapter);//from  www.j a  v  a  2  s  .  c  om
    final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    final SharedPreferences.Editor editor = settings.edit();
    String prevInput = settings.getString("prev_fe_input", "");

    final EditText input = new EditText(this);
    input.setText(prevInput);
    new AlertDialog.Builder(this).setTitle(getString(R.string.fe_search_title))
            .setMessage(getString(R.string.fe_search_message)).setView(input)
            .setPositiveButton(getString(R.string.ok_text), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    final String value = input.getText().toString();
                    editor.putString("prev_fe_input", value);
                    editor.commit();
                    mProgressDialog = ProgressDialog.show(DownloaderFE.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 List<DownloadItem> dil = retrieveList(value);
                                mHandler.post(new Runnable() {
                                    public void run() {
                                        dlAdapter.addList(dil);
                                        mProgressDialog.dismiss();
                                    }
                                });
                            } catch (final Exception e) {
                                mHandler.post(new Runnable() {
                                    public void run() {
                                        mProgressDialog.dismiss();
                                        new AlertDialog.Builder(DownloaderFE.this)
                                                .setTitle(R.string.downloader_connection_error)
                                                .setMessage(
                                                        getString(R.string.downloader_connection_error_message)
                                                                + e.toString())
                                                .setPositiveButton(getString(R.string.ok_text),
                                                        new DialogInterface.OnClickListener() {
                                                            @Override
                                                            public void onClick(DialogInterface dialog,
                                                                    int which) {
                                                                finish();
                                                            }
                                                        })
                                                .create().show();
                                    }
                                });
                            }

                        }
                    }.start();

                }
            }).setNegativeButton(getString(R.string.cancel_text), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    finish();
                }
            }).create().show();
}

From source file:net.networksaremadeofstring.rhybudd.DeviceList.java

/** Called when the activity is first created. */
@SuppressWarnings({ "unchecked", "deprecation" })
@Override/*from  w w w. j av a 2 s .  c o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    settings = PreferenceManager.getDefaultSharedPreferences(this);

    setContentView(R.layout.devicelist);
    BugSenseHandler.initAndStartSession(DeviceList.this, "44a76a8c");

    actionbar = getActionBar();
    actionbar.setDisplayHomeAsUpEnabled(true);
    actionbar.setHomeButtonEnabled(true);
    actionbar.setTitle("Infrastructure");

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

    BugSenseHandler.initAndStartSession(DeviceList.this, "44a76a8c");

    handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Toast.makeText(DeviceList.this,
                        "An error was encountered;\r\n" + msg.getData().getString("exception"),
                        Toast.LENGTH_LONG).show();
            } else if (msg.what == 1) {
                dialog.setMessage("Refresh Complete!");
                this.sendEmptyMessageDelayed(2, 1000);
            } else if (msg.what == 2) {
                dialog.dismiss();
                adapter = new ZenossDeviceAdaptor(DeviceList.this, listOfZenossDevices);
                list.setAdapter(adapter);
                ((TextView) findViewById(R.id.ServerCountLabel))
                        .setText("Monitoring " + DeviceCount + " servers");
            }
        }
    };

    try {
        listOfZenossDevices = (List<ZenossDevice>) getLastNonConfigurationInstance();
    } catch (Exception e) {
        listOfZenossDevices = null;
        //BugSenseHandler.log("DeviceList", e);
    }

    if (listOfZenossDevices == null || listOfZenossDevices.size() < 1) {
        listOfZenossDevices = new ArrayList<ZenossDevice>();
        DBGetThread();
    } else {
        adapter = new ZenossDeviceAdaptor(DeviceList.this, listOfZenossDevices);
        list.setAdapter(adapter);
    }
}

From source file:io.selendroid.server.ServerInstrumentation.java

@SuppressWarnings("unchecked")
@Override/*from   ww  w  .j  a  va 2 s  .  c  o  m*/
public void onCreate(Bundle arguments) {
    Handler mainThreadHandler = new Handler();
    this.args = new InstrumentationArguments(arguments);

    mainActivityName = arguments.getString("main_activity");

    int parsedServerPort = 0;

    try {
        String port = args.getServerPort();
        if (port != null && !port.isEmpty()) {
            parsedServerPort = Integer.parseInt(port);
        }
    } catch (NumberFormatException ex) {
        SelendroidLogger
                .error("Unable to parse the value of server_port key, defaulting to " + this.serverPort);
        parsedServerPort = this.serverPort;
    }

    if (isValidPort(parsedServerPort)) {
        this.serverPort = parsedServerPort;
    }

    SelendroidLogger.info("Instrumentation initialized with main activity: " + mainActivityName);
    instance = this;

    final Context context = getTargetContext();
    if (args.isLoadExtensions()) {
        extensionLoader = new ExtensionLoader(context, ExternalStorage.getExtensionDex().getAbsolutePath());
        String bootstrapClassNames = args.getBootstrapClassNames();
        if (bootstrapClassNames != null) {
            extensionLoader.runBeforeApplicationCreateBootstrap(instance, bootstrapClassNames.split(","));
        }
    } else {
        extensionLoader = new ExtensionLoader(context);
    }

    // Queue bootstrapping and starting of the main activity on the main thread.
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            UncaughtExceptionHandling.clearCrashLogFile();
            UncaughtExceptionHandling.setGlobalExceptionHandler();

            if (args.isLoadExtensions() && args.getBootstrapClassNames() != null) {
                extensionLoader.runAfterApplicationCreateBootstrap(instance,
                        args.getBootstrapClassNames().split(","));
            }

            startMainActivity();
            try {
                startServer();
            } catch (Exception e) {
                SelendroidLogger.error("Failed to start selendroid server", e);
            }
        }
    });
}

From source file:it.uniroma2.foundme.studente.UnFollowCourseActivity.java

public static void populateView(String[] result) {
    courses = new String[result.length];
    System.arraycopy(result, 0, courses, 0, result.length);
    List<Map<String, String>> data = new ArrayList<Map<String, String>>();

    for (int i = 0; i < result.length; i++) {
        Map<String, String> datum = new HashMap<String, String>(2);
        if (i == 0 && result[0].equalsIgnoreCase(Variables_it.NO_COURSE)) {
            datum.put(Variables_it.COURSE, result[0]);
            datum.put(Variables_it.PROF, "");
            data.add(datum);/*from ww  w . ja v a 2  s  .  c  o  m*/
            break;
        } else {
            String[] items = result[i].split(",");
            datum.put(Variables_it.COURSE, items[0]);
            datum.put(Variables_it.PROF, items[1]);
            data.add(datum);
        }
    }
    //creo l'adapter
    SimpleAdapter adapter = new SimpleAdapter(context, data, android.R.layout.simple_list_item_2,
            new String[] { Variables_it.COURSE, Variables_it.PROF },
            new int[] { android.R.id.text1, android.R.id.text2 });
    lvCorsiSeguiti.setAdapter(adapter);

    swipeUnfollow.setColorSchemeColors(0xff429874, 0xffffffff, 0xff429874, 0xffffffff);
    swipeUnfollow.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            swipeUnfollow.setRefreshing(true);
            (new Handler()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        getCourse(false);
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    swipeUnfollow.setRefreshing(false);
                }
            }, 3000);
        }
    });

    lvCorsiSeguiti.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (!courses[position].equalsIgnoreCase(Variables_it.NO_COURSE))
                alertMessage(courses[position]);
        }
    });

    lvCorsiSeguiti.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
            if (firstVisibleItem == 0)
                swipeUnfollow.setEnabled(true);
            else
                swipeUnfollow.setEnabled(false);
        }
    });
}