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:io.github.carlorodriguez.alarmon.AlarmClockService.java

private void handleStart(Intent intent) {
    if (intent != null && intent.hasExtra(COMMAND_EXTRA)) {
        Bundle extras = intent.getExtras();
        int command = extras.getInt(COMMAND_EXTRA, COMMAND_UNKNOWN);

        final Handler handler = new Handler();
        final Runnable maybeShutdown = new Runnable() {
            @Override/*from w w w.  ja va 2s  .c  om*/
            public void run() {
                if (pendingAlarms.size() == 0) {
                    stopSelf();
                }
            }
        };

        switch (command) {
        case COMMAND_NOTIFICATION_REFRESH:
            refreshNotification();
            handler.post(maybeShutdown);
            break;
        case COMMAND_DEVICE_BOOT:
            fixPersistentSettings();
            handler.post(maybeShutdown);
            break;
        case COMMAND_TIMEZONE_CHANGE:
            if (AppSettings.isDebugMode(getApplicationContext())) {
                Toast.makeText(getApplicationContext(), "TIMEZONE CHANGE, RESCHEDULING...", Toast.LENGTH_SHORT)
                        .show();
            }
            for (long alarmId : pendingAlarms.pendingAlarms()) {
                scheduleAlarm(alarmId);
                if (AppSettings.isDebugMode(getApplicationContext())) {
                    Toast.makeText(getApplicationContext(), "ALARM " + alarmId, Toast.LENGTH_SHORT).show();
                }
            }
            handler.post(maybeShutdown);
            break;
        default:
            throw new IllegalArgumentException("Unknown service command.");
        }
    }
}

From source file:com.cranberrygame.cordova.plugin.ad.admob.AdmobSplit.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void handleLayoutChangeOverlap() {
    //http://stackoverflow.com/questions/24539578/cordova-plugin-listening-to-device-orientation-change-is-it-possible
    //http://developer.android.com/reference/android/view/View.OnLayoutChangeListener.html
    //https://gitshell.com/lvxudong/A530_packages_app_Camera/blob/master/src/com/android/camera/ActivityBase.java
    //plugin.getWebView().addOnLayoutChangeListener(new View.OnLayoutChangeListener(){//only for ~cordova4
    //plugin.getWebView().getRootView().addOnLayoutChangeListener(new View.OnLayoutChangeListener(){//only for ~cordova4
    //plugin.getWebView().getView().addOnLayoutChangeListener(new View.OnLayoutChangeListener(){//only for cordova5~
    getView(plugin.getWebView()).addOnLayoutChangeListener(new View.OnLayoutChangeListener() {

        @Override//from   www.j a  v  a  2s  . com
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
                int oldRight, int oldBottom) {
            if (left == oldLeft && top == oldTop && right == oldRight && bottom == oldBottom) {
                return;
            }

            Log.d(LOG_TAG, "onLayoutChange");
            //Util.alert(cordova.getActivity(), "onLayoutChange");

            int orientation = Util.getDisplayRotation(plugin.getCordova().getActivity());
            if (orientation != lastOrientation) {
                Log.d(LOG_TAG, String.format("orientation: %d", orientation));
                //Util.alert(cordova.getActivity(), String.format("orientation: %d", orientation));
                if (bannerPreviousSize != null && bannerPreviousSize.equals("SMART_BANNER")) {
                    Log.d(LOG_TAG, String.format("position: %s, size: %s", bannerPreviousPosition,
                            bannerPreviousSize));
                    //Util.alert(cordova.getActivity(), String.format("position: %s, size: %s", position, size));

                    //split
                    if (bannerView != null) {
                        //if banner is showing
                        ViewGroup parentView = (ViewGroup) bannerView.getParent();
                        if (parentView != null) {
                            //parentView.removeView(bannerView);
                            //bannerView.destroy();
                            //bannerView = null;
                            Log.d(LOG_TAG, String.format("position: %s, size: %s", bannerPreviousPosition,
                                    bannerPreviousSize));
                            //Util.alert(cordova.getActivity(), String.format("position: %s, size: %s", position, size));

                            //http://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android
                            final Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    _showBannerAd(bannerPreviousPosition, bannerPreviousSize);
                                }
                            }, 1);//after 1ms            
                        }
                    }
                }
            }

            lastOrientation = orientation;
        }
    });
}

From source file:com.andrewshu.android.reddit.threads.BitmapManager.java

public void fetchBitmapOnThread(final String urlString, final ImageView imageView,
        final ProgressBar indeterminateProgressBar, final Activity act) {
    SoftReference<Bitmap> ref = mCache.get(urlString);
    if (ref != null && ref.get() != null) {
        imageView.setImageBitmap(ref.get());
        return;//from   w  ww.j ava2 s .c  o m
    }

    final Runnable progressBarShow = new Runnable() {
        public void run() {
            if (indeterminateProgressBar != null) {
                imageView.setVisibility(View.GONE);
                indeterminateProgressBar.setVisibility(View.VISIBLE);
            }
        }
    };
    final Runnable progressBarHide = new Runnable() {
        public void run() {
            if (indeterminateProgressBar != null) {
                indeterminateProgressBar.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
            }
        }
    };

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

    Thread thread = new Thread() {
        @Override
        public void run() {
            if (indeterminateProgressBar != null && act != null)
                act.runOnUiThread(progressBarShow);
            Bitmap bitmap = fetchBitmap(urlString);
            Message message = handler.obtainMessage(1, bitmap);
            handler.sendMessage(message);
        }
    };
    thread.start();
}

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

/**
 * TODO - Geofencing spoofed location//  w w  w  .j  a  v  a2 s .  c o m
 */
public static void saveSpoofedGeolocationValuesFromPreferences() {
    Handler handler = new Handler();

    if (Boolean
            .valueOf(Hybris.getSharedPreferenceString(InternalConstants.KEY_PREF_GEOFENCING_SPOOF_OVERRIDE))) {
        double lat = 0;
        double longi = 0;
        float rad = 0;

        try {
            lat = Double.valueOf(
                    getSharedPreferences().getString(InternalConstants.KEY_PREF_GEOFENCING_LATITUDE, ""));
            longi = Double.valueOf(
                    getSharedPreferences().getString(InternalConstants.KEY_PREF_GEOFENCING_LONGITUDE, ""));
            rad = Float.valueOf(
                    getSharedPreferences().getString(InternalConstants.KEY_PREF_GEOFENCING_RADIUS, ""));
        } catch (Exception e) {
        }

        if (lat != 0 && longi != 0 && rad != 0) {

            GeofenceObject geofence = new GeofenceObject();
            geofence.setId("spoofedGeofence");
            geofence.setExpirationDuration(Geofence.NEVER_EXPIRE);
            geofence.setLatitude(lat);
            geofence.setLongitude(longi);
            geofence.setRadius(rad);
            geofence.setTransitionType(Geofence.GEOFENCE_TRANSITION_ENTER);

            String tmpJson = "{\"geoPoint\":{\"longitude\":11.585745,\"latitude\":48.155121},\"storeImages\":[{\"url\":\"\\/medias\\/electronics-store-365x246-01.jpg?context=bWFzdGVyOjo6aW1hZ2VzOjo6MTA3NTE5Ojo6aW1hZ2UvanBlZzo6OmltYWdlcy9oMDIvaDYyLzg3OTY2ODc0MDA5OTAuanBnOjo6OTkzNWM1NTk5YjhmYjU3Y2QzNDc1NWFmMDBlM2NkMzk2YjFkZTlmYjI5Y2VkZjNkZGNhOGZkN2UxMWE4ZTBhMw\",\"format\":\"store\"},{\"url\":\"\\/medias\\/electronics-store-65x65-01.jpg?context=bWFzdGVyOjo6aW1hZ2VzOjo6MjA2OTM6OjppbWFnZS9qcGVnOjo6aW1hZ2VzL2g5Zi9oMDQvODc5NjY4NzU5NzU5OC5qcGc6OjpjZGEzMjdmZjI1NmMxMTE2ODNlYTBmYTg0MTA1YjAzNjkyMWJkNTViYWFjMmI3NTRmZmZlYTZhNmU3MjZlMDRk\",\"format\":\"cartIcon\"}],\"openingHours\":{\"specialDays\":[{\"closed\":true,\"date\":\"2013-09-16 04:00:00.0 UTC\",\"openingTime\":{\"minute\":0,\"hour\":0},\"formattedDate\":\"16\\/09\\/13\",\"name\":\"Respect for the Aged Day\",\"closingTime\":{\"minute\":0,\"hour\":0}},{\"closed\":true,\"date\":\"2013-09-23 04:00:00.0 UTC\",\"openingTime\":{\"minute\":0,\"hour\":0},\"formattedDate\":\"23\\/09\\/13\",\"name\":\"Autumnal Equinox Day\",\"closingTime\":{\"minute\":0,\"hour\":0}},{\"closed\":true,\"date\":\"2013-10-14 04:00:00.0 UTC\",\"openingTime\":{\"minute\":0,\"hour\":0},\"formattedDate\":\"14\\/10\\/13\",\"name\":\"Health-Sports Day\",\"closingTime\":{\"minute\":0,\"hour\":0}},{\"closed\":true,\"date\":\"2013-11-03 04:00:00.0 UTC\",\"openingTime\":{\"minute\":0,\"hour\":0},\"formattedDate\":\"03\\/11\\/13\",\"name\":\"Culture Day\",\"closingTime\":{\"minute\":0,\"hour\":0}},{\"closed\":true,\"date\":\"2013-11-23 05:00:00.0 UTC\",\"openingTime\":{\"minute\":0,\"hour\":0},\"formattedDate\":\"23\\/11\\/13\",\"name\":\"Labour Thanksgiving Day\",\"closingTime\":{\"minute\":0,\"hour\":0}},{\"closed\":true,\"date\":\"2013-12-23 05:00:00.0 UTC\",\"openingTime\":{\"minute\":0,\"hour\":0},\"formattedDate\":\"23\\/12\\/13\",\"name\":\"The Emperor's Birthday\",\"closingTime\":{\"minute\":0,\"hour\":0}}],\"weekDays\":[{\"weekDay\":\"Mon\",\"openingTime\":{\"minute\":0,\"formattedHour\":\"09:00\",\"hour\":9},\"closed\":false,\"closingTime\":{\"minute\":0,\"formattedHour\":\"20:00\",\"hour\":8}},{\"weekDay\":\"Tue\",\"openingTime\":{\"minute\":0,\"formattedHour\":\"09:00\",\"hour\":9},\"closed\":false,\"closingTime\":{\"minute\":0,\"formattedHour\":\"20:00\",\"hour\":8}},{\"weekDay\":\"Wed\",\"openingTime\":{\"minute\":0,\"formattedHour\":\"09:00\",\"hour\":9},\"closed\":false,\"closingTime\":{\"minute\":0,\"formattedHour\":\"20:00\",\"hour\":8}},{\"weekDay\":\"Thu\",\"openingTime\":{\"minute\":0,\"formattedHour\":\"09:00\",\"hour\":9},\"closed\":false,\"closingTime\":{\"minute\":0,\"formattedHour\":\"20:00\",\"hour\":8}},{\"weekDay\":\"Fri\",\"openingTime\":{\"minute\":0,\"formattedHour\":\"09:00\",\"hour\":9},\"closed\":false,\"closingTime\":{\"minute\":0,\"formattedHour\":\"20:00\",\"hour\":8}},{\"weekDay\":\"Sat\",\"openingTime\":{\"minute\":0,\"formattedHour\":\"10:00\",\"hour\":10},\"closed\":false,\"closingTime\":{\"minute\":0,\"formattedHour\":\"20:00\",\"hour\":8}},{\"weekDay\":\"Sun\",\"closed\":true}],\"code\":\"electronics-japan-standard-hours\"},\"address\":{\"id\":\"8796144107543\",\"phone\":\"+00 0000 0000\",\"postalCode\":\"000000\",\"formattedAddress\":\"Street Name, Street Number, 000000, Test Town, Germany\",\"town\":\"Test Town\",\"line1\":\"Street Name\",\"line2\":\"Street Number\",\"country\":{\"isocode\":\"DE\",\"name\":\"Germany\"}},\"name\":\"Test Geolocation Notification hybris\",\"features\":[{\"value\":\"Wheelchair Access\",\"key\":\"wheelchair\"},{\"value\":\"Creche\",\"key\":\"creche\"},{\"value\":\"Buy Online Pick Up In Store\",\"key\":\"buyOnlinePickupInStore\"}],\"formattedDistance\":\"3.7 Km\",\"url\":\"\\/store\\/Test Geolocation Notification hybris?lat=48.1367203&long=11.576754&q=munich\"}";
            Store store = JsonUtils.fromJson(tmpJson, Store.class);

            geofence.setAssociatedObjectFullClassName(Store.class.getCanonicalName());
            geofence.setAssociatedObject(store);
            geofence.setIntentClassDestination(StoreLocatorDetailActivity.class.getCanonicalName());
            geofence.setIntentObjectKeyName(DataConstants.INTENT_OBJECT_STORE);
            geofence.setNotificationTitle(
                    Hybris.getAppContext().getString(R.string.geofence_notification_store_title));
            geofence.setNotificationText(Hybris.getAppContext()
                    .getString(R.string.geofence_notification_store_text, store.getName()));

            // Saving the object for future 
            Geofencable geofenceJsonSharedPreferences = GeofenceJsonSharedPreferences.createGeofencable(
                    Hybris.getAppContext(), DataConstants.PREFIX_GEOFENCE_SHARED_PREFERENCES);
            geofenceJsonSharedPreferences.saveGeofence(geofence);

            // We force the activation on the geofencing
            GeofenceUtils.enableGeofencesMonitoring(geofenceJsonSharedPreferences, handler, 1, 2);
        }

    } else {
        // We enable/disable the geofencing with the normal method to not disable it by mistake if geofencing is switc
        enableGeofencing();
    }

}

From source file:com.zzisoo.toylibrary.fragment.ToyListViewFragment.java

@Override
public void onResume() {
    super.onResume();
    mToyListView.setAdapter(mAdapter);//from   ww  w.  jav a 2 s .c  om
    if (mAdapter != null) {
        final int lastClickedPostion = mAdapter.getClickedPostion();
        final int lastClickedPrePostion = lastClickedPostion - 1 < 0 ? 0 : lastClickedPostion - 1;
        Log.e(TAG, "mClickedPostion:" + lastClickedPostion);
        mToyListView.scrollToPosition(lastClickedPrePostion);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mToyListView.smoothScrollToPosition(lastClickedPostion);
            }
        }, 100);
    }
}

From source file:com.layer.atlas.messenger.AtlasMessagesScreen.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.uiHandler = new Handler();
    this.app = (MessengerApp) getApplication();

    setContentView(R.layout.atlas_screen_messages);

    boolean convIsNew = getIntent().getBooleanExtra(EXTRA_CONVERSATION_IS_NEW, false);
    String convUri = getIntent().getStringExtra(EXTRA_CONVERSATION_URI);
    if (convUri != null) {
        Uri uri = Uri.parse(convUri);/*from ww w .  j a  va  2s  . com*/
        conv = app.getLayerClient().getConversation(uri);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(convUri.hashCode()); // Clear notifications for this Conversation
    }

    participantsPicker = (AtlasParticipantPicker) findViewById(R.id.atlas_screen_messages_participants_picker);
    participantsPicker.init(new String[] { app.getLayerClient().getAuthenticatedUserId() },
            app.getParticipantProvider());
    if (convIsNew) {
        participantsPicker.setVisibility(View.VISIBLE);
    }

    messageComposer = (AtlasMessageComposer) findViewById(R.id.atlas_screen_messages_message_composer);
    messageComposer.init(app.getLayerClient(), conv);
    messageComposer.setListener(new AtlasMessageComposer.Listener() {
        public boolean beforeSend(Message message) {
            boolean conversationReady = ensureConversationReady();
            if (!conversationReady)
                return false;

            // push
            preparePushMetadata(message);
            return true;
        }

    });

    messageComposer.registerMenuItem("Photo", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            String fileName = "cameraOutput" + System.currentTimeMillis() + ".jpg";
            photoFile = new File(getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES), fileName);
            final Uri outputUri = Uri.fromFile(photoFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            if (debug)
                Log.w(TAG, "onClick() requesting photo to file: " + fileName + ", uri: " + outputUri);
            startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
        }
    });

    messageComposer.registerMenuItem("Image", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            // in onCreate or any event where your want the user to select a file
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_CODE_GALLERY);
        }
    });

    messageComposer.registerMenuItem("Location", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            if (lastKnownLocation == null) {
                Toast.makeText(v.getContext(), "Inserting Location: Location is unknown yet",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            String locationString = "{\"lat\":" + lastKnownLocation.getLatitude() + ", \"lon\":"
                    + lastKnownLocation.getLongitude() + "}";
            MessagePart part = app.getLayerClient().newMessagePart(Atlas.MIME_TYPE_ATLAS_LOCATION,
                    locationString.getBytes());
            Message message = app.getLayerClient().newMessage(Arrays.asList(part));

            preparePushMetadata(message);
            conv.send(message);

            if (debug)
                Log.w(TAG, "onSendLocation() loc:  " + locationString);
        }
    });

    messagesList = (AtlasMessagesList) findViewById(R.id.atlas_screen_messages_messages_list);
    messagesList.init(app.getLayerClient(), app.getParticipantProvider());
    if (USE_QUERY) {
        Query<Message> query = Query.builder(Message.class)
                .predicate(new Predicate(Message.Property.CONVERSATION, Predicate.Operator.EQUAL_TO, conv))
                .sortDescriptor(new SortDescriptor(Message.Property.POSITION, SortDescriptor.Order.ASCENDING))
                .build();
        messagesList.setQuery(query);
    } else {
        messagesList.setConversation(conv);
    }

    messagesList.setItemClickListener(new ItemClickListener() {
        public void onItemClick(Cell cell) {
            if (Atlas.MIME_TYPE_ATLAS_LOCATION.equals(cell.messagePart.getMimeType())) {
                String jsonLonLat = new String(cell.messagePart.getData());
                JSONObject json;
                try {
                    json = new JSONObject(jsonLonLat);
                    double lon = json.getDouble("lon");
                    double lat = json.getDouble("lat");
                    Intent openMapIntent = new Intent(Intent.ACTION_VIEW);
                    String uriString = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f", lat, lon, 18,
                            lat, lon);
                    final Uri geoUri = Uri.parse(uriString);
                    openMapIntent.setData(geoUri);
                    if (openMapIntent.resolveActivity(getPackageManager()) != null) {
                        startActivity(openMapIntent);
                        if (debug)
                            Log.w(TAG, "onItemClick() starting Map: " + uriString);
                    } else {
                        if (debug)
                            Log.w(TAG, "onItemClick() No Activity to start Map: " + geoUri);
                    }
                } catch (JSONException ignored) {
                }
            } else if (cell instanceof ImageCell) {
                Intent intent = new Intent(AtlasMessagesScreen.this.getApplicationContext(),
                        AtlasImageViewScreen.class);
                app.setParam(intent, cell);
                startActivity(intent);
            }
        }
    });

    typingIndicator = (AtlasTypingIndicator) findViewById(R.id.atlas_screen_messages_typing_indicator);
    typingIndicator.init(conv,
            new AtlasTypingIndicator.DefaultTypingIndicatorCallback(app.getParticipantProvider()));

    // location manager for inserting locations:
    this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    prepareActionBar();
}

From source file:com.liferay.alerts.activity.ComposeActivity.java

protected void showKeyboard() {
    final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    Runnable runnable = new Runnable() {

        @Override//from  ww  w.  j a va2s.  c  om
        public void run() {
            manager.showSoftInput(_edit, InputMethodManager.SHOW_IMPLICIT);
        }

    };

    int delay = getResources().getInteger(R.integer.compose_show_keyboard_delay);

    Handler handler = new Handler();
    handler.postDelayed(runnable, delay);

    _edit.setKeyboardHideListener(new KeyboardHideListener() {

        @Override
        public void onHide() {
            finish();
        }

    });
}

From source file:it.uniroma2.foundme.studente.FollowCourseActivity.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);/* www  .  j  a  v  a  2s. c o m*/
            break;
        } else {
            String[] items = result[i].split(",");
            String ap = items[0] + items[1];
            datum.put(Variables_it.COURSE, ap);
            datum.put(Variables_it.PROF, items[2]);
            data.add(datum);
        }
    }
    //creo l'adapter
    final 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 });
    lvTuttiCorsi.setAdapter(adapter);
    lvTuttiCorsi.setTextFilterEnabled(true);

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

    lvTuttiCorsi.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]);
        }
    });

    lvTuttiCorsi.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)
                swipeFollow.setEnabled(true);
            else
                swipeFollow.setEnabled(false);
        }
    });

    etFilter.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
}

From source file:com.aniruddhc.acemusic.player.LauncherActivity.LauncherActivity.java

@SuppressLint("NewApi")
@Override/*from   ww w  .j a  v a  2 s.c o m*/
public void onCreate(Bundle savedInstanceState) {

    setTheme(R.style.AppThemeNoActionBar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launcher);

    mContext = this;
    mActivity = this;
    mApp = (Common) mContext.getApplicationContext();
    mHandler = new Handler();

    //Increment the start count. This value will be used to determine when the library should be rescanned.
    int startCount = mApp.getSharedPreferences().getInt("START_COUNT", 1);
    mApp.getSharedPreferences().edit().putInt("START_COUNT", startCount + 1).commit();

    //Save the dimensions of the layout for later use on KitKat devices.
    final RelativeLayout launcherRootView = (RelativeLayout) findViewById(R.id.launcher_root_view);
    launcherRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {

            try {

                int screenDimens[] = new int[2];
                int screenHeight = 0;
                int screenWidth = 0;
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    //API levels 14, 15 and 16.
                    screenDimens = getTrueDeviceResolution();
                    screenWidth = screenDimens[0];
                    screenHeight = screenDimens[1];

                } else {
                    //API levels 17+.
                    Display display = getWindowManager().getDefaultDisplay();
                    DisplayMetrics metrics = new DisplayMetrics();
                    display.getRealMetrics(metrics);
                    screenHeight = metrics.heightPixels;
                    screenWidth = metrics.widthPixels;

                }

                int layoutHeight = launcherRootView.getHeight();
                int layoutWidth = launcherRootView.getWidth();

                int extraHeight = screenHeight - layoutHeight;
                int extraWidth = screenWidth = layoutWidth;

                mApp.getSharedPreferences().edit().putInt("KITKAT_HEIGHT", layoutHeight).commit();
                mApp.getSharedPreferences().edit().putInt("KITKAT_WIDTH", layoutWidth).commit();
                mApp.getSharedPreferences().edit().putInt("KITKAT_HEIGHT_LAND", layoutWidth - extraHeight)
                        .commit();
                mApp.getSharedPreferences().edit().putInt("KITKAT_WIDTH_LAND", screenHeight).commit();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    });

    //Build the music library based on the user's scan frequency preferences.
    int scanFrequency = mApp.getSharedPreferences().getInt("SCAN_FREQUENCY", 5);
    int updatedStartCount = mApp.getSharedPreferences().getInt("START_COUNT", 1);

    //Launch the appropriate activity based on the "FIRST RUN" flag.
    if (mApp.getSharedPreferences().getBoolean(Common.FIRST_RUN, true) == true) {

        //Create the default Playlists directory if it doesn't exist.
        File playlistsDirectory = new File(Environment.getExternalStorageDirectory() + "/Playlists/");
        if (!playlistsDirectory.exists() || !playlistsDirectory.isDirectory()) {
            playlistsDirectory.mkdir();
        }

        //Disable equalizer for HTC devices by default.
        if (mApp.getSharedPreferences().getBoolean(Common.FIRST_RUN, true) == true
                && Build.PRODUCT.contains("HTC")) {
            mApp.getSharedPreferences().edit().putBoolean("EQUALIZER_ENABLED", false).commit();
        }

        //Send out a test broadcast to initialize the homescreen/lockscreen widgets.
        sendBroadcast(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME));

        Intent intent = new Intent(this, WelcomeActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

    } else if (mApp.isBuildingLibrary()) {
        buildingLibraryMainText = (TextView) findViewById(R.id.building_music_library_text);
        buildingLibraryInfoText = (TextView) findViewById(R.id.building_music_library_info);
        buildingLibraryLayout = (RelativeLayout) findViewById(R.id.building_music_library_layout);

        buildingLibraryInfoText.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
        buildingLibraryInfoText.setPaintFlags(
                buildingLibraryInfoText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        buildingLibraryMainText.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
        buildingLibraryMainText.setPaintFlags(
                buildingLibraryMainText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        buildingLibraryMainText.setText(R.string.jams_is_building_library);
        buildingLibraryLayout.setVisibility(View.VISIBLE);

        //Initialize the runnable that will fire once the scan process is complete.
        mHandler.post(scanFinishedCheckerRunnable);

    } else if (mApp.getSharedPreferences().getBoolean("RESCAN_ALBUM_ART", false) == true) {

        buildingLibraryMainText = (TextView) findViewById(R.id.building_music_library_text);
        buildingLibraryInfoText = (TextView) findViewById(R.id.building_music_library_info);
        buildingLibraryLayout = (RelativeLayout) findViewById(R.id.building_music_library_layout);

        buildingLibraryInfoText.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
        buildingLibraryInfoText.setPaintFlags(
                buildingLibraryInfoText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        buildingLibraryMainText.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
        buildingLibraryMainText.setPaintFlags(
                buildingLibraryMainText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        buildingLibraryMainText.setText(R.string.jams_is_caching_artwork);
        initScanProcess(0);

    } else if ((mApp.getSharedPreferences().getBoolean("REBUILD_LIBRARY", false) == true)
            || (scanFrequency == 0 && mApp.isScanFinished() == false)
            || (scanFrequency == 1 && mApp.isScanFinished() == false && updatedStartCount % 3 == 0)
            || (scanFrequency == 2 && mApp.isScanFinished() == false && updatedStartCount % 5 == 0)
            || (scanFrequency == 3 && mApp.isScanFinished() == false && updatedStartCount % 10 == 0)
            || (scanFrequency == 4 && mApp.isScanFinished() == false && updatedStartCount % 20 == 0)) {

        buildingLibraryMainText = (TextView) findViewById(R.id.building_music_library_text);
        buildingLibraryInfoText = (TextView) findViewById(R.id.building_music_library_info);
        buildingLibraryLayout = (RelativeLayout) findViewById(R.id.building_music_library_layout);

        buildingLibraryInfoText.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
        buildingLibraryInfoText.setPaintFlags(
                buildingLibraryInfoText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        buildingLibraryMainText.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
        buildingLibraryMainText.setPaintFlags(
                buildingLibraryMainText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

        initScanProcess(1);

    } else {

        //Check if this activity was called from Settings.
        if (getIntent().hasExtra("UPGRADE")) {
            if (getIntent().getExtras().getBoolean("UPGRADE") == true) {
                mExplicitShowTrialFragment = true;
            } else {
                mExplicitShowTrialFragment = false;
            }

        }

        //initInAppBilling();
        launchMainActivity();
    }

    //Fire away a report to Google Analytics.
    try {
        if (mApp.isGoogleAnalyticsEnabled() == true) {
            EasyTracker easyTracker = EasyTracker.getInstance(this);
            easyTracker.send(MapBuilder.createEvent("ACE startup.", // Event category (required)
                    "User started ACE.", // Event action (required)
                    "User started ACE.", // Event label
                    null) // Event value
                    .build());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}