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.lostad.app.base.util.DownloadUtil.java

public static void downFileAsyn(final Activity ctx, final String upgradeUrl, final String savedPath,
        final MyCallback<Boolean> callback) {
    final ProgressDialog xh_pDialog = new ProgressDialog(ctx);
    // ?/*from  w  w  w  .  j  a v  a2  s  .c  o m*/
    xh_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    // ProgressDialog 
    xh_pDialog.setTitle("???");
    // ProgressDialog???
    xh_pDialog.setMessage("...");
    // ProgressDialog
    // xh_pDialog.setIcon(R.drawable.img2);
    // ProgressDialog ??? false ??
    xh_pDialog.setIndeterminate(false);
    // ProgressDialog ?
    // xh_pDialog.setProgress(100);
    // ProgressDialog ???
    xh_pDialog.setCancelable(true);
    // ProgressDialog
    xh_pDialog.show();

    new Thread() {
        public void run() {

            boolean downloadSuccess = true;
            FileOutputStream fileOutputStream = null;
            try {
                Looper.prepare();
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(upgradeUrl);

                File f = new File(savedPath);
                if (!f.exists()) {
                    f.createNewFile();
                }

                HttpResponse response = client.execute(get);
                HttpEntity entity = response.getEntity();
                // ?
                Long length = entity.getContentLength();
                xh_pDialog.setMax(length.intValue());
                //
                InputStream is = entity.getContent();
                fileOutputStream = null;

                if (is != null && length > 0) {

                    fileOutputStream = new FileOutputStream(f);

                    byte[] buf = new byte[1024];
                    int ch = -1;
                    int count = 0;
                    while ((ch = is.read(buf)) != -1) {

                        if (xh_pDialog.isShowing()) {
                            fileOutputStream.write(buf, 0, ch);
                            // ?
                            count += ch;
                            xh_pDialog.setProgress(count);
                        } else {
                            downloadSuccess = false;
                            break;// ?
                        }
                    }

                } else {
                    callback.onCallback(false);
                }

                if (downloadSuccess && fileOutputStream != null) {
                    xh_pDialog.dismiss();
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    callback.onCallback(true);// ?
                }
                Looper.loop();
            } catch (FileNotFoundException e) {
                xh_pDialog.dismiss();
                e.printStackTrace();
                callback.onCallback(false);
                xh_pDialog.dismiss();
            } catch (Exception e) {
                xh_pDialog.dismiss();
                e.printStackTrace();
                callback.onCallback(false);
            } finally {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }.start();

}

From source file:cc.wulian.smarthomev5.fragment.singin.handler.DecodeThread.java

@Override
public void run() {
    Looper.prepare();
    handler = new DecodeHandler(scanHandlerResult, hints);
    handlerInitLatch.countDown();
    Looper.loop();
}

From source file:com.ubikod.urbantag.ContentViewerActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle extras = getIntent().getExtras();

    /* If we are coming from Notification delete notification */
    if (extras.getInt(NotificationHelper.FROM_NOTIFICATION, -1) == NotificationHelper.NEW_CONTENT_NOTIF) {
        NotificationHelper notificationHelper = new NotificationHelper(this);
        notificationHelper.closeContentNotif();
    } else if (extras.getInt(NotificationHelper.FROM_NOTIFICATION, -1) == NotificationHelper.NEW_PLACE_NOTIF) {
        NotificationHelper notificationHelper = new NotificationHelper(this);
        notificationHelper.closePlaceNotif();
    }/*from w  w w  .jav a 2s  . co  m*/

    /* Fetch content info */
    ContentManager contentManager = new ContentManager(new DatabaseHelper(this, null));
    Log.i(UrbanTag.TAG, "View content : " + extras.getInt(CONTENT_ID));
    this.content = contentManager.get(extras.getInt(CONTENT_ID));
    if (this.content == null) {
        Toast.makeText(this, R.string.error_occured, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    setTitle(content.getName());
    com.actionbarsherlock.app.ActionBar actionBar = this.getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.content_viewer);

    /* Find webview and create url for content */
    final WebView webView = (WebView) findViewById(R.id.webview);
    final String URL = UrbanTag.API_URL + ACTION_GET_CONTENT.replaceAll("%", "" + this.content.getId());

    /* Display progress animation */
    final ProgressDialog progress = ProgressDialog.show(this, "",
            this.getResources().getString(R.string.loading_content), false, true,
            new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    timeOutHandler.interrupt();
                    webView.stopLoading();
                    ContentViewerActivity.this.finish();
                }

            });

    /* Go fetch content */
    contentFetcher = new Thread(new Runnable() {

        DefaultHttpClient httpClient;

        @Override
        public void run() {
            Looper.prepare();
            Log.i(UrbanTag.TAG, "Fetching content...");
            httpClient = new DefaultHttpClient();
            try {
                String responseBody = httpClient.execute(new HttpGet(URL), new BasicResponseHandler());
                webView.loadDataWithBaseURL("fake://url/for/encoding/hack...", responseBody, mimeType, encoding,
                        "");
                timeOutHandler.interrupt();
                if (progress.isShowing())
                    progress.dismiss();
            } catch (ClientProtocolException cpe) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                timeOutHandler.interrupt();
                progress.cancel();
            } catch (IOException ioe) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                timeOutHandler.interrupt();
                progress.cancel();
            }

            Looper.loop();
        }

    });
    contentFetcher.start();

    /* TimeOut Handler */
    timeOutHandler = new Thread(new Runnable() {
        private int INCREMENT = 1000;

        @Override
        public void run() {
            Looper.prepare();
            try {
                for (int time = 0; time < TIMEOUT; time += INCREMENT) {
                    Thread.sleep(INCREMENT);
                }

                Log.w(UrbanTag.TAG, "TimeOut !");
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });

                contentFetcher.interrupt();
                progress.cancel();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Looper.loop();

        }

    });
    timeOutHandler.start();

}

From source file:de.nware.app.hsDroid.logic.LoginThread.java

License:asdf

@Override
public void run() {
    // flags setzen
    mStoppingThread = false;/* w  w w  .j  a  v  a  2  s.  c o  m*/
    mThreadStatus = STATE_RUNNING;

    // prepare Looper
    Looper.prepare();

    mThreadHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case HANLDER_MSG_LOGIN:
                try {
                    doLogin();

                } catch (Exception e) {
                    mThreadStatus = STATE_ERROR;
                    Message oMessage = mParentHandler.obtainMessage();
                    Bundle oBundle = new Bundle();
                    String strMessage = e.getMessage();
                    oBundle.putString("Message", strMessage);
                    oMessage.setData(oBundle);
                    oMessage.what = MESSAGE_ERROR;
                    mParentHandler.sendMessage(oMessage);
                } catch (Throwable e) {
                    Log.e("Login Handler", e.getMessage());
                    e.printStackTrace();
                }
                break;

            case HANLDER_MSG_LOGOUT:
                try {
                    doLogout();

                } catch (Exception e) {
                    mThreadStatus = STATE_ERROR;
                    Message oMessage = mParentHandler.obtainMessage();
                    Bundle oBundle = new Bundle();
                    String strMessage = e.getMessage();
                    oBundle.putString("Message", strMessage);
                    oMessage.setData(oBundle);
                    oMessage.what = MESSAGE_ERROR;
                    mParentHandler.sendMessage(oMessage);
                } catch (Throwable e) {
                    Log.e("Login Handler", e.getMessage());
                    e.printStackTrace();
                }
                break;
            case HANLDER_MSG_KILL:
                getLooper().quit();
                break;
            default:
                break;
            }
        }
    };

    Looper.loop();
}

From source file:com.tcl.lzhang1.mymusic.AppException.java

/**
 * Handle exception.//from   w  w w .ja  v a 2s . com
 * 
 * @param ex the ex
 * @return true, if successful
 */
private boolean handleException(final Throwable ex) {

    if (ex == null) {

        return false;
    } else {

        ex.printStackTrace();

    }

    final Context context = AppManager.getInstance().currentActivity();

    if (context == null) {
        return false;
    }

    final String crashReport = getCrashReport(context, ex);
    System.out.println("AppException.handleException()");
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            saveLog(ex);
            UIHelper.sendAppCrashReport(context, crashReport);
            Looper.loop();
        }

    }.start();

    return true;
}

From source file:net.evecom.androidecssp.base.BaseActivity.java

/**  */
protected void toastInOtherThread(String strMsg, int L1S0) {
    Looper.prepare();//from   w  w w  . j  a va2s. com
    Toast.makeText(getApplicationContext(), strMsg, L1S0).show();
    Looper.loop();
}

From source file:com.ihelpoo.app.AppException.java

/**
 * ?:?&??//  w ww .  j  av a  2 s.c o m
 * @param ex
 * @return true:??;?false
 */
private boolean handleException(Throwable ex) {
    if (ex == null) {
        return false;
    }

    final Context context = AppManager.getAppManager().currentActivity();

    if (context == null) {
        return false;
    }

    final String crashReport = getCrashReport(context, ex);
    //?&??
    new Thread() {
        public void run() {
            Looper.prepare();
            UIHelper.sendAppCrashReport(context, crashReport);
            Looper.loop();
        }

    }.start();
    return true;
}

From source file:com.jtxdriggers.android.ventriloid.VentriloidService.java

@Override
public void onCreate() {
    stopForeground(true);//from w  ww .  ja va  2 s .  c  o  m

    new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            handler = new Handler();
            Looper.loop();
        }
    }).start();

    items = new ItemData(this);
    player = new Player(this);
    recorder = new Recorder(this);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    if (prefs.getString("notification_type", "Text to Speech").equals("Text to Speech")) {
        ttsActive = true;
        tts = new TextToSpeech(VentriloidService.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS)
                    ttsActive = true;
                else {
                    ttsActive = false;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "TTS Initialization faled.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    } else if (prefs.getString("notification_type", "Text to Speech").equals("Ringtone"))
        ringtoneActive = true;

    registerReceiver(activityReceiver, new IntentFilter(ACTIVITY_RECEIVER));

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    voiceActivation = prefs.getBoolean("voice_activation", false);
    threshold = voiceActivation ? 55.03125 : -1;
    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibrate = prefs.getBoolean("vibrate", true);

    queue = new ConcurrentLinkedQueue<VentriloEventData>();

    //VentriloInterface.debuglevel(65535);
    new Thread(eventHandler).start();
}

From source file:com.oneguy.recognize.engine.GoogleStreamingEngine.java

@Override
public void run() {
    Looper.prepare();/*w  ww  . j a  v a  2 s .c  om*/
    mHandler = new Handler() {
        @Override
        public synchronized void handleMessage(Message msg) {
            int event = msg.what;
            Object arg = msg.obj;
            Log.d(TAG, "engine state:" + getStateName(mState) + " event:" + getEventName(event));
            switch (mState) {
            case STATE_IDLE:
                switch (event) {
                case EVENT_START:
                    connectUpStream();
                    break;
                case EVENT_SHUTDOWN:
                    shutAll();
                    break;
                case EVENT_STREAM_ERROR:
                    abortWithError();
                    break;
                case EVENT_STOP:
                case EVENT_AUDIO_CHUNK:
                case EVENT_RESPONSE:
                    Log.d(TAG, "drop event:" + event + " state:IDLE");
                    break;
                }
                break;
            case STATE_UP_STREAM_CONNECTED:
                switch (event) {
                case EVENT_STOP:
                    sendStopPacketAndGetResponse();
                    break;
                case EVENT_SHUTDOWN:
                    shutAll();
                    break;
                case EVENT_AUDIO_CHUNK:
                    transmitAudioUpstream((byte[]) arg);
                    break;
                case EVENT_STREAM_ERROR:
                    abortWithError();
                    break;
                case EVENT_START:
                case EVENT_RESPONSE:
                    Log.d(TAG, "drop event:" + event + " state:IDLE");
                    break;
                }
                break;
            case STATE_WAITING_DOWNSTREAM_RESULTS:
                switch (event) {
                case EVENT_START:
                    break;
                case EVENT_STOP:
                    break;
                case EVENT_SHUTDOWN:
                    shutAll();
                    break;
                case EVENT_AUDIO_CHUNK:
                    break;
                case EVENT_RESPONSE:
                    processResponse((StreamResponse) arg);
                    break;
                case EVENT_STREAM_ERROR:
                    abortWithError();
                    break;
                }
                break;
            case STATE_SHUTDOWN:
                Log.e(TAG, "impossible,STATE_SHUTDOWN should not receive event!");
                break;
            }
        }

    };
    Looper.loop();
}

From source file:com.android.fastlibrary.AppException.java

/**
 * ?:?&??//w  w  w.  j  a  va 2  s .  co m
 *
 * @param ex
 * @return true:??;?false
 */
private boolean handleException(Throwable ex) {
    if (ex == null) {
        return false;
    }

    final Context context = AppManager.getInstance().getTopActivity();

    if (context == null) {
        return false;
    }

    final String crashReport = getCrashReport(context, ex);
    //?&??
    new Thread() {
        public void run() {
            Looper.prepare();
            UIHelper.sendAppCrashReport(context, crashReport);
            Looper.loop();
        }

    }.start();
    return true;
}