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:com.llkj.cm.restfull.network.NetworkConnection.java

/**
 * By default the user agent is empty. If you want to use the standard Android user agent, call this method before using the
 * <code>retrieveResponseFromService</code> methods
 * /* ww w  .j  a  v a2  s .  c om*/
 * @param context The context
 */
public static void generateDefaultUserAgent(final Context context) {
    if (sDefaultUserAgent != null) {
        return;
    }

    try {
        Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class,
                WebView.class);
        constructor.setAccessible(true);
        try {
            WebSettings settings = constructor.newInstance(context, null);
            sDefaultUserAgent = settings.getUserAgentString();
        } finally {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        if (Thread.currentThread().getName().equalsIgnoreCase("main")) {
            WebView webview = new WebView(context);
            sDefaultUserAgent = webview.getSettings().getUserAgentString();
        } else {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    WebView webview = new WebView(context);
                    sDefaultUserAgent = webview.getSettings().getUserAgentString();
                    Looper.loop();
                }
            };
            thread.start();
        }
    }
}

From source file:org.smssecure.smssecure.notifications.MessageNotifier.java

public static void sendDeliveryToast(final Context context, final String recipientName) {
    new Thread() {
        @Override//from   w ww. j  a v  a 2  s . c  o m
        public void run() {
            Looper.prepare();
            Toast.makeText(context.getApplicationContext(),
                    context.getString(R.string.MessageNotifier_message_received, recipientName),
                    Toast.LENGTH_LONG).show();
            Looper.loop();
        }
    }.start();
}

From source file:com.gtosoft.libvoyager.net.GTONet.java

/**
 * Creates a new "worker" thread, to which we can post new work to be performed asynchronously from the main (UI) thread. 
 */// www .  ja  va2 s . c  o  m
public void startWorkerThread() {
    if (mWorkerThread != null)
        return;

    // create a new thread. 
    mWorkerThread = new Thread() {
        public void run() {
            //mWorkerHandler.getLooper();
            Looper.prepare();

            // set the worker to a new handler owned by this thead. 
            mWorkerHandler = new Handler();

            // main loop. just loop, sleeping, waiting for work. 
            while (1 == 1) {
                Looper.loop();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    break; // break out of the while loop, kills the thread. 
                }

            } // end while loop. 
            Looper.myLooper().quit();
        }// end of thread run() 
    };
    mWorkerThread.start();

    // sleep for a second while thread starts... Prevents calling tasks from hitting it before it has a chance to start!
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        return;
    }

}

From source file:ru.dublgis.androidhelpers.mobility.CellListener.java

public synchronized boolean start() {
    Log.d(TAG, "start");
    try {/* w  ww  .  ja v a  2 s .c om*/
        if (mManager == null) {
            mManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
        }

        Runnable listenRunnable = new Runnable() {
            @Override
            public void run() {
                if (mManager != null) {
                    try {
                        Looper.prepare();
                        mListenerLooper = Looper.myLooper();
                        mListener = new CellListenerImpl();
                        mManager.listen(mListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
                        Looper.loop();
                        mManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
                    } catch (Throwable ex) {
                        Log.e(TAG, "Failed to start TelephonyManager listener", ex);
                    }
                }
            }
        };

        mListenerThread = new Thread(listenRunnable, "Listen TelephonyManager");
        mListenerThread.start();
        return true;
    } catch (Throwable e) {
        Log.e(TAG, "Exception while starting cell listener: ", e);
        return false;
    }
}

From source file:cn.xiongyihui.wificar.Car.java

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

    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            String url = "http://" + mIp + "/cgi-bin/serial?" + (String) msg.obj;
            URI uri = URI.create(url);

            HttpResponse httpResponse;
            DefaultHttpClient httpClient = new DefaultHttpClient();
            try {
                httpResponse = httpClient.execute(new HttpGet(uri));
            } catch (IOException e) {
                Log.v(TAG, "Unable to connect to car.");

                mState = STATE_UNCONNECTED;

                return;
            }

            char get;
            try {
                get = (char) httpResponse.getEntity().getContent().read();
            } catch (IOException e) {
                Log.v(TAG, "Unkown situation when connecting car.");

                mState = STATE_UNKOWN;
                return;
            }

            mState = mCommandList.indexOf(Character.toString(get));
        }
    };

    changeTo(STATE_STOP);

    Looper.loop();
}

From source file:com.vuzix.samplewebrtc.android.SessionChannel.java

private synchronized void open() {
    close();//from w  w  w .j a va2  s.co  m

    // ???
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            mSendHandler = new Handler();
            Looper.loop();
        }
    }.start();

    mConnectionThread = new ConnectionThread();
    mConnectionThread.start();
}

From source file:org.mobiletrial.license.connect.RestClient.java

public void post(final String path, final JSONObject requestJson, final OnRequestFinishedListener listener) {
    Thread t = new Thread() {
        public void run() {
            Looper.prepare(); //For Preparing Message Pool for the child Thread

            // Register Schemes for http and https
            final SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry.register(new Scheme("https", createAdditionalCertsSSLSocketFactory(), 443));

            final HttpParams params = new BasicHttpParams();
            final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
            HttpClient client = new DefaultHttpClient(cm, params);

            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit

            HttpResponse response;/*  w ww  .j  av  a  2  s . c  o m*/
            try {
                String urlStr = mServiceUrl.toExternalForm();
                if (urlStr.charAt(urlStr.length() - 1) != '/')
                    urlStr += "/";
                urlStr += path;
                URI actionURI = new URI(urlStr);

                HttpPost post = new HttpPost(actionURI);
                StringEntity se = new StringEntity(requestJson.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);

                /* Checking response */
                if (response == null) {
                    listener.gotError(ERROR_CONTACTING_SERVER);
                    Log.w(TAG, "Error contacting licensing server.");
                    return;
                }
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    Log.w(TAG, "An error has occurred on the licensing server.");
                    listener.gotError(ERROR_SERVER_FAILURE);
                    return;
                }

                /* Convert response to JSON */
                InputStream in = response.getEntity().getContent(); //Get the data in the entity
                String responseStr = inputstreamToString(in);
                listener.gotResponse(responseStr);

            } catch (ClientProtocolException e) {
                Log.w(TAG, "ClientProtocolExeption:  " + e.getLocalizedMessage());
                e.printStackTrace();
            } catch (IOException e) {
                Log.w(TAG, "Error on contacting server: " + e.getLocalizedMessage());
                listener.gotError(ERROR_CONTACTING_SERVER);
            } catch (URISyntaxException e) {
                //This shouldn't happen   
                Log.w(TAG, "Could not build URI.. Your service Url is propably not a valid Url:  "
                        + e.getLocalizedMessage());
                e.printStackTrace();
            }
            Looper.loop(); //Loop in the message queue
        }
    };
    t.start();
}

From source file:com.prey.actions.location.PreyGooglePlayServiceLocation.java

protected void startLocationUpdates() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || (ActivityCompat.checkSelfPermission(ctx,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(ctx,
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
        try {/* w ww  .  j av  a 2s .co  m*/
            Looper.prepare();
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            Looper.loop();
        } catch (Exception e) {
            PreyLogger.d("Error startLocationUpdates: " + e.getMessage());
        }
    }

}

From source file:com.facebook.android.Places.java

public void getLocation() {
    /*// w w  w  . j a v a2 s .  co  m
     * launch a new Thread to get new location
     */
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            dialog = ProgressDialog.show(Places.this, "", getString(R.string.fetching_location), false, true,
                    new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            showToast("No location fetched.");
                        }
                    });

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            if (locationListener == null) {
                locationListener = new MyLocationListener();
            }

            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String provider = lm.getBestProvider(criteria, true);
            if (provider != null && lm.isProviderEnabled(provider)) {
                lm.requestLocationUpdates(provider, 1, 0, locationListener, Looper.getMainLooper());
            } else {
                /*
                 * GPS not enabled, prompt user to enable GPS in the
                 * Location menu
                 */
                new AlertDialog.Builder(Places.this).setTitle(R.string.enable_gps_title)
                        .setMessage(getString(R.string.enable_gps))
                        .setPositiveButton(R.string.gps_settings, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivityForResult(
                                        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
                                        0);
                            }
                        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Places.this.finish();
                            }
                        }).show();
            }
            Looper.loop();
        }
    }.start();
}

From source file:de.qspool.clementineremote.backend.ClementinePlayerConnection.java

public void run() {
    // Start the thread
    mNotificationManager = (NotificationManager) App.mApp.getSystemService(Context.NOTIFICATION_SERVICE);

    Looper.prepare();//  w w w  .ja  v  a 2 s.co  m
    mHandler = new ClementineConnectionHandler(this);

    mPebble = new Pebble();

    // Get a Wakelock Object
    PowerManager pm = (PowerManager) App.mApp.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Clementine");

    Resources res = App.mApp.getResources();
    mNotificationHeight = (int) res.getDimension(android.R.dimen.notification_large_icon_height);
    mNotificationWidth = (int) res.getDimension(android.R.dimen.notification_large_icon_width);

    mAudioManager = (AudioManager) App.mApp.getSystemService(Context.AUDIO_SERVICE);
    mClementineMediaButtonEventReceiver = new ComponentName(App.mApp.getPackageName(),
            ClementineMediaButtonEventReceiver.class.getName());

    mMediaButtonBroadcastReceiver = new ClementineMediaButtonEventReceiver();

    fireOnConnectionReady();

    Looper.loop();
}