Example usage for android.content Context getMainLooper

List of usage examples for android.content Context getMainLooper

Introduction

In this page you can find the example usage for android.content Context getMainLooper.

Prototype

public abstract Looper getMainLooper();

Source Link

Document

Return the Looper for the main thread of the current process.

Usage

From source file:crow.api.ApiClient.java

public ApiClient(Context context, Parser parser, ThreadPoolExecutor threadPool, Cache cache,
        CookieStore store) {/*from   w  ww.j a va2s. c o  m*/
    this.parser = parser;
    this.threadPool = threadPool;
    this.cache = cache;
    this.handler = new Handler(context.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SEND_MESSAGE:
                RequestRunnable<?, ?> r = (RequestRunnable<?, ?>) msg.obj;
                r.sendMessageToCallback();
                break;
            }
        }
    };
    // Create a local instance of cookie store
    cookieStore = store;
    // Create local HTTP context
    localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:org.chromium.chrome.browser.media.remote.NotificationTransportControl.java

private NotificationTransportControl(Context context) {
    this.mContext = context;
    mHandler = new Handler(context.getMainLooper());
    mPlayDescription = context.getResources().getString(R.string.accessibility_play);
    mPauseDescription = context.getResources().getString(R.string.accessibility_pause);
}

From source file:jahirfiquitiva.iconshowcase.activities.AltWallpaperViewerActivity.java

private Handler handler(Context context) {
    return new Handler(context.getMainLooper());
}

From source file:com.aretha.content.image.AsyncImageLoader.java

private AsyncImageLoader(Context context) {
    mContext = context.getApplicationContext();
    mFileCacheManager = new FileCacheManager(context);
    mExecutor = Executors.newCachedThreadPool();
    mTaskList = new LinkedList<ImageLoadingTask>();
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    mScreenWidth = displayMetrics.widthPixels;
    mScreenHeight = displayMetrics.heightPixels;
    // will notify the main thread
    mImageLoadedHandler = new ImageLoadHandler(context.getMainLooper());
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

void init(Context m) {
    master = m;/*  w  w w  .  j  av a2 s . co  m*/
    masterHandler = new Handler(m.getMainLooper());
    notificationManager = (NotificationManager) master.getSystemService(Context.NOTIFICATION_SERVICE);

    Application app;
    if (m instanceof Application) {
        app = (Application) m;
    } else if (m instanceof Service) {
        app = ((Service) m).getApplication();
    } else if (m instanceof Activity) {
        app = ((Activity) m).getApplication();
    } else
        throw new ClassCastException("MemorizingTrustManager context must be either Activity or Service!");

    File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE);
    keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE);

    poshCacheDir = app.getFilesDir().getAbsolutePath() + "/posh_cache/";

    appKeyStore = loadAppKeyStore();
}

From source file:com.dngames.mobilewebcam.PhotoSettings.java

public static void GETSettings(final Context context) {
    // check for new settings when done
    final SharedPreferences prefs = context.getSharedPreferences(MobileWebCam.SHARED_PREFS_NAME, 0);
    final String settingsurl = prefs.getString("remote_config_url", "");
    final int settingsfreq = Math.max(1, PhotoSettings.getEditInt(context, prefs, "remote_config_every", 1));
    final String login = prefs.getString("remote_config_login", "");
    final String password = prefs.getString("remote_config_password", "");
    final boolean noToasts = prefs.getBoolean("no_messages", false);
    if (settingsurl.length() > 0 && gLastGETSettingsPictureCnt < MobileWebCam.gPictureCounter
            && (MobileWebCam.gPictureCounter % settingsfreq) == 0) {
        gLastGETSettingsPictureCnt = MobileWebCam.gPictureCounter;

        Handler h = new Handler(context.getMainLooper());
        h.post(new Runnable() {
            @Override//from  ww w . j  a  v  a  2 s  . c o m
            public void run() {
                new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... params) {
                        try {
                            DefaultHttpClient httpclient = new DefaultHttpClient();
                            if (login.length() > 0) {
                                try {
                                    ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
                                            new AuthScope(null, -1),
                                            new UsernamePasswordCredentials(login, password));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    if (e.getMessage() != null)
                                        MobileWebCam.LogE("http login " + e.getMessage());
                                    else
                                        MobileWebCam.LogE("http: unable to log in");

                                    return null;
                                }
                            }
                            HttpGet get = new HttpGet(settingsurl);
                            HttpResponse response = httpclient.execute(get);
                            HttpEntity ht = response.getEntity();
                            BufferedHttpEntity buf = new BufferedHttpEntity(ht);
                            InputStream is = buf.getContent();
                            BufferedReader r = new BufferedReader(new InputStreamReader(is));
                            StringBuilder total = new StringBuilder();
                            String line;
                            while ((line = r.readLine()) != null)
                                total.append(line + "\n");

                            if (ht.getContentType().getValue().startsWith("text/plain"))
                                return total.toString();
                            else
                                return "GET Config Error!\n" + total.toString();
                        } catch (Exception e) {
                            e.printStackTrace();
                            if (e.getMessage() != null) {
                                MobileWebCam.LogE(e.getMessage());
                                return "GET Config Error!\n" + e.getMessage();
                            }
                        }

                        return null;
                    }

                    @Override
                    protected void onPostExecute(String result) {
                        if (result != null) {
                            if (result.startsWith("GET Config Error!\n")) {
                                if (!noToasts)
                                    Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
                            } else {
                                PhotoSettings.GETSettings(context, result, prefs);
                            }
                        } else if (!noToasts)
                            Toast.makeText(context, "GET config failed!", Toast.LENGTH_SHORT).show();
                    }
                }.execute();
            }
        });
    }
}

From source file:org.goseumdochi.android.leash.EfficientAnimation.java

private static void loadFromXml(final int resourceId, final Context context,
        final OnDrawableLoadedListener onDrawableLoadedListener) {
    new Thread(new Runnable() {
        @Override//from  w w w .  j  a  v  a  2  s .  c  o  m
        public void run() {
            final ArrayList<EaFrame> frames = new ArrayList<>();

            XmlResourceParser parser = context.getResources().getXml(resourceId);

            try {
                int eventType = parser.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_DOCUMENT) {

                    } else if (eventType == XmlPullParser.START_TAG) {

                        if (parser.getName().equals("item")) {
                            byte[] bytes = null;

                            for (int i = 0; i < parser.getAttributeCount(); i++) {
                                String attrName = parser.getAttributeName(i);
                                if (attrName.endsWith("drawable")) {
                                    int resId = Integer.parseInt(parser.getAttributeValue(i).substring(1));
                                    bytes = IOUtils.toByteArray(context.getResources().openRawResource(resId));
                                }
                            }

                            EaFrame frame = new EaFrame();
                            frame.bytes = bytes;
                            frames.add(frame);
                        }

                    } else if (eventType == XmlPullParser.END_TAG) {

                    } else if (eventType == XmlPullParser.TEXT) {

                    }

                    eventType = parser.next();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Run on UI Thread
            new Handler(context.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    if (onDrawableLoadedListener != null) {
                        onDrawableLoadedListener.onDrawableLoaded(frames);
                    }
                }
            });
        }
    }).run();
}

From source file:com.androidinspain.deskclock.alarms.AlarmStateManager.java

/**
 * This will set the alarm instance to the SNOOZE_STATE and update
 * the application notifications and schedule any state changes that need
 * to occur in the future./*from w ww.  ja va 2  s.c om*/
 *
 * @param context  application context
 * @param instance to set state to
 */
public static void setSnoozeState(final Context context, AlarmInstance instance, boolean showToast) {
    // Stop alarm if this instance is firing it
    AlarmService.stopAlarm(context, instance);

    // Calculate the new snooze alarm time
    final int snoozeMinutes = DataModel.getDataModel().getSnoozeLength();
    Calendar newAlarmTime = Calendar.getInstance();
    newAlarmTime.add(Calendar.MINUTE, snoozeMinutes);

    // Update alarm state and new alarm time in db.
    LogUtils.i("Setting snoozed state to instance " + instance.mId + " for "
            + AlarmUtils.getFormattedTime(context, newAlarmTime));
    instance.setAlarmTime(newAlarmTime);
    instance.mAlarmState = AlarmInstance.SNOOZE_STATE;
    AlarmInstance.updateInstance(context.getContentResolver(), instance);

    // Setup instance notification and scheduling timers
    AlarmNotifications.showSnoozeNotification(context, instance);
    scheduleInstanceStateChange(context, instance.getAlarmTime(), instance, AlarmInstance.FIRED_STATE);

    // Display the snooze minutes in a toast.
    if (showToast) {
        final Handler mainHandler = new Handler(context.getMainLooper());
        final Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                String displayTime = String.format(context.getResources()
                        .getQuantityText(com.androidinspain.deskclock.R.plurals.alarm_alert_snooze_set,
                                snoozeMinutes)
                        .toString(), snoozeMinutes);
                Toast.makeText(context, displayTime, Toast.LENGTH_LONG).show();
            }
        };
        mainHandler.post(myRunnable);
    }

    // Instance time changed, so find next alarm that will fire and notify system
    updateNextAlarm(context);
}

From source file:com.kaltura.playersdk.PlayerViewController.java

private void setupPlayerViewController(final Context context) {
    mPowerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE);
    // Get a handler that can be used to post to the main thread
    Handler mainHandler = new Handler(context.getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override/*ww w.ja v a 2  s .c  om*/
        public void run() {
            if (!ChromecastHandler.initialized)
                ChromecastHandler.initialize(context, new OnCastDeviceChangeListener() {

                    @Override
                    public void onCastDeviceChange(CastDevice oldDevice, CastDevice newDevice) {
                        if (ChromecastHandler.selectedDevice != null) {
                            notifyKPlayer("trigger", new String[] { "chromecastDeviceConnected" });
                        } else {
                            notifyKPlayer("trigger", new String[] { "chromecastDeviceDisConnected" });
                        }
                        //                                    createPlayerInstance();
                    }
                }, new OnCastRouteDetectedListener() {
                    @Override
                    public void onCastRouteDetected() {
                        setChromecastVisiblity();
                    }
                });
        }
    };
    mainHandler.post(myRunnable);
}

From source file:com.android.deskclock.alarms.AlarmStateManager.java

/**
 * This will set the alarm instance to the SNOOZE_STATE and update
 * the application notifications and schedule any state changes that need
 * to occur in the future.// www .j av a  2s  .  c om
 *
 * @param context application context
 * @param instance to set state to
 *
 */
public static void setSnoozeState(final Context context, AlarmInstance instance, boolean showToast) {
    // Stop alarm if this instance is firing it
    AlarmService.stopAlarm(context, instance);

    // Calculate the new snooze alarm time
    String snoozeMinutesStr = Utils.getDefaultSharedPreferences(context)
            .getString(SettingsActivity.KEY_ALARM_SNOOZE, DEFAULT_SNOOZE_MINUTES);
    final int snoozeMinutes = Integer.parseInt(snoozeMinutesStr);
    Calendar newAlarmTime = Calendar.getInstance();
    newAlarmTime.add(Calendar.MINUTE, snoozeMinutes);

    // Update alarm state and new alarm time in db.
    LogUtils.i("Setting snoozed state to instance " + instance.mId + " for "
            + AlarmUtils.getFormattedTime(context, newAlarmTime));
    instance.setAlarmTime(newAlarmTime);
    instance.mAlarmState = AlarmInstance.SNOOZE_STATE;
    AlarmInstance.updateInstance(context.getContentResolver(), instance);

    // Setup instance notification and scheduling timers
    AlarmNotifications.showSnoozeNotification(context, instance);
    scheduleInstanceStateChange(context, instance.getAlarmTime(), instance, AlarmInstance.FIRED_STATE);

    // Display the snooze minutes in a toast.
    if (showToast) {
        final Handler mainHandler = new Handler(context.getMainLooper());
        final Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                String displayTime = String.format(context.getResources()
                        .getQuantityText(R.plurals.alarm_alert_snooze_set, snoozeMinutes).toString(),
                        snoozeMinutes);
                Toast.makeText(context, displayTime, Toast.LENGTH_LONG).show();
            }
        };
        mainHandler.post(myRunnable);
    }

    // Instance time changed, so find next alarm that will fire and notify system
    updateNextAlarm(context);
}