Example usage for android.os Looper loop

List of usage examples for android.os Looper loop

Introduction

In this page you can find the example usage for android.os Looper loop.

Prototype

public static void loop() 

Source Link

Document

Run the message queue in this thread.

Usage

From source file:uk.org.rivernile.edinburghbustracker.android.Application.java

/**
 * Check for updates to the bus stop database. This may happen automatically
 * if 24 hours have elapsed since the last check, or if the user has forced
 * the action. If a database update is found, then the new database is
 * downloaded and placed in the correct location.
 * //from  www  .ja  v a  2  s .c o  m
 * @param context The context.
 * @param force True if the user forced the check, false if not.
 */
public static void checkForDBUpdates(final Context context, final boolean force) {
    // Check to see if the user wants their database automatically updated.
    final SharedPreferences sp = context.getSharedPreferences(PreferencesActivity.PREF_FILE, 0);
    final boolean autoUpdate = sp.getBoolean(PREF_DATABASE_AUTO_UPDATE, true);
    final SharedPreferences.Editor edit = sp.edit();

    // Continue to check if the user has enabled it, or a check has been
    // forced (from the Preferences).
    if (autoUpdate || force) {
        if (!force) {
            // If it has not been forced, check the last update time. It is
            // only checked once per day. Abort if it is too soon.
            long lastCheck = sp.getLong("lastUpdateCheck", 0);
            if ((System.currentTimeMillis() - lastCheck) < 86400000)
                return;
        }

        // Construct the checking URL.
        final StringBuilder sb = new StringBuilder();
        sb.append(DB_API_CHECK_URL);
        sb.append(ApiKey.getHashedKey());
        sb.append("&random=");
        // A random number is used so networks don't cache the HTTP
        // response.
        sb.append(random.nextInt());
        try {
            // Do connection stuff.
            final URL url = new URL(sb.toString());
            sb.setLength(0);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                final BufferedInputStream is = new BufferedInputStream(conn.getInputStream());

                if (!url.getHost().equals(conn.getURL().getHost())) {
                    is.close();
                    conn.disconnect();
                    return;
                }

                // Read the incoming data.
                int data;
                while ((data = is.read()) != -1) {
                    sb.append((char) data);
                }
            } finally {
                // Whether there's an error or not, disconnect.
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            return;
        } catch (IOException e) {
            return;
        }

        String topoId;
        try {
            // Parse the JSON and get the topoId from it.
            final JSONObject jo = new JSONObject(sb.toString());
            topoId = jo.getString("topoId");
        } catch (JSONException e) {
            return;
        }

        // If there's topoId then it cannot continue.
        if (topoId == null || topoId.length() == 0)
            return;

        // Get the current topoId from the database.
        final BusStopDatabase bsd = BusStopDatabase.getInstance(context.getApplicationContext());
        final String dbTopoId = bsd.getTopoId();

        // If the topoIds match, write our check time to SharedPreferences.
        if (topoId.equals(dbTopoId)) {
            edit.putLong("lastUpdateCheck", System.currentTimeMillis());
            edit.commit();
            if (force) {
                // It was forced, alert the user there is no update
                // available.
                Looper.prepare();
                Toast.makeText(context, R.string.bus_stop_db_no_updates, Toast.LENGTH_LONG).show();
                Looper.loop();
            }
            return;
        }

        // There is an update available. Empty the StringBuilder then create
        // the URL to get the new database information.
        sb.setLength(0);
        sb.append(DB_UPDATE_CHECK_URL);
        sb.append(random.nextInt());
        sb.append("&key=");
        sb.append(ApiKey.getHashedKey());

        try {
            // Connection stuff.
            final URL url = new URL(sb.toString());
            sb.setLength(0);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                final BufferedInputStream is = new BufferedInputStream(conn.getInputStream());

                if (!url.getHost().equals(conn.getURL().getHost())) {
                    is.close();
                    conn.disconnect();
                    return;
                }

                int data;
                // Read the incoming data.
                while ((data = is.read()) != -1) {
                    sb.append((char) data);
                }
            } finally {
                // Whether there's an error or not, disconnect.
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            return;
        } catch (IOException e) {
            return;
        }

        String dbUrl, schemaVersion, checksum;
        try {
            // Get the data from tje returned JSON.
            final JSONObject jo = new JSONObject(sb.toString());
            dbUrl = jo.getString("db_url");
            schemaVersion = jo.getString("db_schema_version");
            topoId = jo.getString("topo_id");
            checksum = jo.getString("checksum");
        } catch (JSONException e) {
            // There was an error parsing the JSON, it cannot continue.
            return;
        }

        // Make sure the returned schema name is compatible with the one
        // the app uses.
        if (!BusStopDatabase.SCHEMA_NAME.equals(schemaVersion))
            return;
        // Some basic sanity checking on the parameters.
        if (topoId == null || topoId.length() == 0)
            return;
        if (dbUrl == null || dbUrl.length() == 0)
            return;
        if (checksum == null || checksum.length() == 0)
            return;

        // Make sure an update really is available.
        if (!topoId.equals(dbTopoId)) {
            // Update the database.
            updateStopsDB(context, dbUrl, checksum);
        } else if (force) {
            // Tell the user there is no update available.
            Looper.prepare();
            Toast.makeText(context, R.string.bus_stop_db_no_updates, Toast.LENGTH_LONG).show();
            Looper.loop();
        }

        // Write to the SharedPreferences the last update time.
        edit.putLong("lastUpdateCheck", System.currentTimeMillis());
        edit.commit();
    }
}

From source file:github.daneren2005.dsub.service.DownloadServiceImpl.java

@Override
public void onCreate() {
    super.onCreate();

    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();//from   ww w .  j a v a 2 s .  c  o  m

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadServiceImpl.this, PowerManager.PARTIAL_WAKE_LOCK);

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, mediaPlayer.getAudioSessionId());
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).start();

    Util.registerMediaButtonEventReceiver(this);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientHelper.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    SharedPreferences prefs = Util.getPreferences(this);
    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    instance = this;
    lifecycleSupport.onCreate();

    if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
        getEqualizerController();
    }
}

From source file:io.autem.MainActivity.java

protected void sendTestMessage(final String chromeToken, final String apiKey) {
    Thread t = new Thread() {

        public void run() {
            Log.i(TAG, "Preparing message");
            Looper.prepare(); //For Preparing Message Pool for the child Thread
            SendMessageService sendMessageService = new SendMessageService();
            sendMessageService.sendMessage(apiKey, chromeToken, "Message Tester", "This is a test.",
                    "Autem Test Contact");
            Looper.loop(); //Loop in the message queue
        }//from  w w w.j  a v a2 s .c o  m
    };
    t.start();
}

From source file:com.eboxlive.ebox.image.ImageCache.java

public void initDiskCache() {
    synchronized (mDiskCacheLock) {
        // ? //from  w  w w .j  a  v a 2  s . c  om
        File file = mCacheParams.diskCacheDir;
        if (!file.exists()) {
            file.mkdirs();
        }
        if (ImageCache.getUsableSpace(mCacheParams.diskCacheDir) < HTTP_CACHE_SIZE) {
            Looper.prepare();
            Toast.makeText(OcApplication.getApplication(), "?,", Toast.LENGTH_LONG)
                    .show();
            Looper.loop();
        }
        mDiskCacheStarting = false;
        mDiskCacheLock.notifyAll();
    }
}

From source file:com.android.pc.ioc.image.ImageCache.java

public void initDiskCache() {
    synchronized (mDiskCacheLock) {
        // ? //w w  w  .j  a  v a 2s . co  m
        File file = mCacheParams.diskCacheDir;
        if (!file.exists()) {
            file.mkdirs();
        }
        if (ImageCache.getUsableSpace(mCacheParams.diskCacheDir) < HTTP_CACHE_SIZE) {
            Looper.prepare();
            Toast.makeText(Ioc.getIoc().getApplication(), "?,", Toast.LENGTH_LONG)
                    .show();
            Looper.loop();
        }
        mDiskCacheStarting = false;
        mDiskCacheLock.notifyAll();
    }
}

From source file:com.smallzhi.autobahn.WebSocketConnection.java

public void connect(String wsUri, String[] wsSubprotocols, WebSocket.ConnectionHandler wsHandler,
        WebSocketOptions options, List<BasicNameValuePair> headers) throws WebSocketException {

    // don't connect if already connected .. user needs to disconnect first
    ///*  w  w  w.ja  va  2  s  .  c  o m*/
    if (mTransportChannel != null && mTransportChannel.isConnected()) {
        throw new WebSocketException("already connected");
    }

    // parse WebSockets URI
    //
    try {
        mWsUri = new URI(wsUri);

        if (!mWsUri.getScheme().equals("ws") && !mWsUri.getScheme().equals("wss")) {
            throw new WebSocketException("unsupported scheme for WebSockets URI");
        }

        if (mWsUri.getScheme().equals("wss")) {
            throw new WebSocketException("secure WebSockets not implemented");
        }

        mWsScheme = mWsUri.getScheme();

        if (mWsUri.getPort() == -1) {
            if (mWsScheme.equals("ws")) {
                mWsPort = 80;
            } else {
                mWsPort = 443;
            }
        } else {
            mWsPort = mWsUri.getPort();
        }

        if (mWsUri.getHost() == null) {
            throw new WebSocketException("no host specified in WebSockets URI");
        } else {
            mWsHost = mWsUri.getHost();
        }

        if (mWsUri.getPath() == null || mWsUri.getPath().equals("")) {
            mWsPath = "/";
        } else {
            mWsPath = mWsUri.getPath();
        }

        if (mWsUri.getQuery() == null || mWsUri.getQuery().equals("")) {
            mWsQuery = null;
        } else {
            mWsQuery = mWsUri.getQuery();
        }

    } catch (URISyntaxException e) {

        throw new WebSocketException("invalid WebSockets URI");
    }

    mWsSubprotocols = wsSubprotocols;
    mWsHeaders = headers;
    mWsHandler = wsHandler;

    // make copy of options!
    mOptions = new WebSocketOptions(options);

    // set connection active
    mActive = true;

    // use asynch connector on short-lived background thread
    new WebSocketConnector().start();

    // Hanlder ??
    Looper.loop();
}

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

/**
 * Called when the activity is first created.
 *///from  w  ww . ja  va 2 s .c  o m
@Override
protected void onCreate(Bundle load) {
    try {
        super.onCreate(load);
    } catch (NullPointerException exceptions) {
        // Unrecoverable Google Maps V1 crash
        Toast.makeText(this, R.string.error_map_nullpointer, Toast.LENGTH_LONG);
    }
    setContentView(R.layout.map);
    Toolbar toolbar = (Toolbar) findViewById(R.id.support_actionbar);
    setSupportActionBar(toolbar);

    findViewById(R.id.mapScreen).setDrawingCacheEnabled(true);
    mUnits = new UnitsI18n(this);
    mLoggerServiceManager = new GPSLoggerServiceManager();

    final Semaphore calulatorSemaphore = new Semaphore(0);
    Thread calulator = new Thread("OverlayCalculator") {
        @Override
        public void run() {
            Looper.prepare();
            mHandler = new Handler();
            calulatorSemaphore.release();
            Looper.loop();
        }
    };
    calulator.start();
    try {
        calulatorSemaphore.acquire();
    } catch (InterruptedException e) {
        Log.e(this, "Failed waiting for a semaphore", e);
    }
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mMapView = (MapView) findViewById(R.id.myMapView);
    setupHardwareAcceleration();
    mMylocation = new FixedMyLocationOverlay(this, mMapView);
    mMapView.setBuiltInZoomControls(true);
    mMapView.setClickable(true);

    TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04),
            (TextView) findViewById(R.id.speedview03), (TextView) findViewById(R.id.speedview02),
            (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) };
    mSpeedtexts = speeds;
    mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed);
    mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude);
    mDistanceView = (TextView) findViewById(R.id.currentDistance);
    mFab = (FloatingActionButton) findViewById(R.id.tracking_control);
    createListeners();

    if (load != null) {
        onRestoreInstanceState(load);
    }
    if (getIntent() != null) {
        handleIntentData(getIntent());
    }
}

From source file:com.lepin.activity.MyLoveCarActivity.java

private void updateCarState() {
    new Thread(new Runnable() {
        @Override/*ww  w.ja v a 2s .c  o m*/
        public void run() {
            String result = "";// ?
            try {
                ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                result = HttpUtil.post((List<NameValuePair>) params, Constant.URL_GETUSERCARINFO,
                        MyLoveCarActivity.this);
            } catch (Exception e) {
                Util.getInstance().log(e.getMessage());
                e.printStackTrace();
            }
            JsonResult<Car> jresult = util.getObjFromJsonResult(result, new TypeToken<JsonResult<Car>>() {
            });
            Looper.prepare();
            if (jresult != null) {
                if (jresult.isSuccess()) {
                    car = jresult.getData();
                    if (car.getState() != null) {
                        if (car.getState().equals(Car.STATE_AUDIT_UNPASS)) {// ?
                            mlSafe.post(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    mlSafe.setText(getResources().getString(R.string.my_car_vefic_faile));
                                }
                            });
                        }
                        if (car.getState().equals(Car.STATE_WAIT_AUDIT)) {// ?
                            mlSafe.post(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    mlSafe.setText(getResources().getString(R.string.my_car_vefic_notdo));
                                }
                            });
                        }
                        if (car.getState().equals(Car.STATE_AUDITING)) {
                            mlSafe.post(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    mlSafe.setText(getResources().getString(R.string.my_car_vefic_doing));
                                    isEidting = false;
                                }
                            });
                        }
                        if (car.getState().equals(Car.STATE_AUDITED)) {
                            mlSafe.post(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    mlSafe.setText(getResources().getString(R.string.my_car_vefic_okdo));
                                    isEidting = false;
                                }
                            });
                        }
                        Looper.loop();
                    }
                }
            }
        }
    }).start();
}

From source file:org.moire.ultrasonic.service.DownloadServiceImpl.java

@SuppressLint("NewApi")
@Override/*  ww  w. j  a  v a 2 s . c om*/
public void onCreate() {
    super.onCreate();

    new Thread(new Runnable() {
        @Override
        public void run() {
            Thread.currentThread().setName("DownloadServiceImpl");

            Looper.prepare();

            if (mediaPlayer != null) {
                mediaPlayer.release();
            }

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadServiceImpl.this, PowerManager.PARTIAL_WAKE_LOCK);

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception(String.format("MediaPlayer error: %d (%d)", what, more)));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, mediaPlayer.getAudioSessionId());
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).start();

    audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    setUpRemoteControlClient();

    if (equalizerAvailable) {
        equalizerController = new EqualizerController(this, mediaPlayer);
        if (!equalizerController.isAvailable()) {
            equalizerController = null;
        } else {
            equalizerController.loadSettings();
        }
    }
    if (visualizerAvailable) {
        visualizerController = new VisualizerController(mediaPlayer);
        if (!visualizerController.isAvailable()) {
            visualizerController = null;
        }
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    instance = this;
    lifecycleSupport.onCreate();
}

From source file:com.android.yijiang.kzx.http.AsyncHttpResponseHandler.java

final public void sendSuccessMessage(int statusCode, Header[] headers, byte[] responseBytes) {
    String content = new String(responseBytes);
    if (content.indexOf("invalid key") != -1 || content.indexOf("token missing") != -1) {
        if (ApplicationController.mCount > 0) {
            return;
        }//from www.  j ava2 s. co m
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                ApplicationController.mCount++;
                MsgTools.toast(ApplicationController.getInstance(), "?,?!",
                        Toast.LENGTH_LONG);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        gotoLogin();
                    }
                }, Toast.LENGTH_SHORT);
                ApplicationController.mCount = 0;
                Looper.loop();
            }
        }).run();
    } else if (content.indexOf("need team") != -1) {
        Intent i = new Intent(ApplicationController.getInstance(), ContentFragmentActivity.class);
        i.putExtra("action", "create_team");
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        ApplicationController.getInstance().startActivity(i);
    } else {
        try {
            final boolean success = new JSONObject(content).optBoolean("success", false);
            final String message = new JSONObject(content).optString("message");
            final String data = new JSONObject(content).optString("data");
            if (!success && "null".equals(data) && StringUtils.isEmpty(message)) {
                gotoLogin();
                return;
            } else if (!success && "null".equals(data) && !StringUtils.isEmpty(message)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        MsgTools.toast(ApplicationController.getInstance(), message, Toast.LENGTH_LONG);
                        sendFinishMessage();
                        Looper.loop();
                    }
                }).run();
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[] { statusCode, headers, responseBytes }));
        }
        sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[] { statusCode, headers, responseBytes }));
    }
}