List of usage examples for android.os Looper loop
public static void loop()
From source file:com.feedhenry.sdk.tests.api.FHSDKTest.java
private void runAsyncRequest(final FHAct pRequest, final FHActCallback pCallback) throws Exception { // The AsyncHttpClient uses Looper & Handlers to implement async http calls. // It requires the calling thread to have a looper attached to it. // When requests are made from the main UI thread, it will work find as the // main UI thread contains a main Looper. // However, if the app creates another Thread which will be used to invoke // the call, it should use the sync mode or attach the looper to the thread // as demoed below. // The main thread that runs the tests doesn't work with Handlers either. Thread testThread = new Thread() { @Override/*from w w w.j av a 2 s . co m*/ public void run() { try { Looper.prepare(); pRequest.executeAsync(new FHActCallback() { @Override public void success(FHResponse pResponse) { System.out.println("Got response " + pResponse.getRawResponse()); pCallback.success(pResponse); Looper.myLooper().quit(); } @Override public void fail(FHResponse pResponse) { System.out.println("Got error response : " + pResponse.getRawResponse()); pCallback.fail(pResponse); Looper.myLooper().quit(); } }); Looper.loop(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; testThread.start(); testThread.join(); }
From source file:com.mediatek.systemupdate.HttpManager.java
private HttpManager(Context context) { mContext = context;/*from ww w.jav a2s .com*/ mDownloadInfo = DownloadInfo.getInstance(mContext); mNotification = new NotifyManager(mContext); initHttpParam(); initHttpClientMgr(); new Thread() { public void run() { Xlog.v(TAG, "thread run " + Thread.currentThread().getName()); Looper.prepare(); mToastHandler = new Handler(Looper.myLooper()) { @Override public void handleMessage(Message msg) { switch (msg.what) { case NETWORK_ERROR_TOAST: Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show(); break; case SERVER_VERSION_ERROR_TOAST: Toast.makeText(mContext, R.string.server_version_error, Toast.LENGTH_LONG).show(); break; default: break; } } }; Looper.loop(); } }.start(); }
From source file:com.flyn.net.asynchttp.AsyncHttpResponseHandler.java
/** * Helper method to send runnable into local handler loop * * @param runnable runnable instance, can be null */// www .j a va 2 s .c o m protected void postRunnable(Runnable runnable) { boolean missingLooper = null == Looper.myLooper(); if (missingLooper) { Looper.prepare(); } if (null == handler) { handler = new ResponderHandler(this); } if (null != runnable) { handler.post(runnable); } if (missingLooper) { Looper.loop(); } }
From source file:com.wen.security.http.AsyncHttpResponseHandler.java
/** * Helper method to send runnable into local handler loop * * @param runnable runnable instance, can be null *//*w w w . j a v a 2s.c o m*/ protected void postRunnable(Runnable runnable) { boolean missingLooper = null == Looper.myLooper(); if (missingLooper) { Looper.prepare(); } if (null != runnable) { handler.post(runnable); } if (missingLooper) { Looper.loop(); } }
From source file:github.daneren2005.dsub.service.DownloadService.java
@Override public void onCreate() { super.onCreate(); final SharedPreferences prefs = Util.getPreferences(this); new Thread(new Runnable() { public void run() { Looper.prepare();/* ww w .j a va 2s.co m*/ mediaPlayer = new MediaPlayer(); mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK); audioSessionId = -1; Integer id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1); if (id != -1) { try { audioSessionId = id; mediaPlayer.setAudioSessionId(audioSessionId); } catch (Throwable e) { audioSessionId = -1; } } if (audioSessionId == -1) { mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { audioSessionId = mediaPlayer.getAudioSessionId(); prefs.edit().putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId).commit(); } catch (Throwable t) { // Froyo or lower } } 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, audioSessionId); i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName()); sendBroadcast(i); } catch (Throwable e) { // Froyo or lower } effectsController = new AudioEffectsController(DownloadService.this, audioSessionId); if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) { getEqualizerController(); } mediaPlayerLooper = Looper.myLooper(); mediaPlayerHandler = new Handler(mediaPlayerLooper); if (runListenersOnInit) { onSongsChanged(); onSongProgress(); onStateUpdate(); } Looper.loop(); } }, "DownloadService").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); 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); mediaRouter = new MediaRouteManager(this); instance = this; shufflePlayBuffer = new ShufflePlayBuffer(this); artistRadioBuffer = new ArtistRadioBuffer(this); lifecycleSupport.onCreate(); }
From source file:com.google.sample.cast.refplayer.Synchronization.java
public void buildSocketConnection() { Thread socket = new Thread("Client") { private Socket clientSocket; BufferedInputStream in;/* w ww . j ava2s .c o m*/ @Override public void run() { Log.d("SocketConnection", "Run"); try { // set server IP and Port //InetAddress serverIp = InetAddress.getByName("10.0.1.27"); // CSCLab Tina //InetAddress serverIp = InetAddress.getByName("10.0.1.103"); // CSCLab Jack InetAddress serverIp = InetAddress.getByName("192.168.1.100"); // CVLab Sever int serverPort = 7777; clientSocket = new Socket(serverIp, serverPort); Log.d("SocketConnection", "Socket built"); BufferedInputStream input = new BufferedInputStream(clientSocket.getInputStream()); // repeat Looper.prepare(); while (clientSocket.isConnected()) { Log.d("SocketConnection", "Connection built"); byte[] data_byte = new byte[1024]; String data = ""; int length; if ((length = input.read(data_byte)) > 0) { data += new String(data_byte, 0, length); Log.d("SocketConnection", "Data: " + data); String subdata[] = data.split(",", 2); String type[] = subdata[0].split(":", 2); String value[] = subdata[1].split(":", 2); Log.d("SocketConnection", "type[1]: " + type[1]); if (type[1].equals("\"gesture\"")) { Log.d("SocketConnection", "gesture"); setVolume(0); } else if (type[1].equals("\"gaze\"")) { Log.d("SocketConnection", "gaze"); setFocus((Character.getNumericValue(value[1].charAt(0)))); } else { Log.d("SocketConnection", "default"); } } } Looper.loop(); } catch (Exception e) { // handle disconnection e.printStackTrace(); Log.e("SocketConnection", e.toString()); // shut down when disconnect finish(); } } }; socket.start(); }
From source file:com.lepin.activity.CarDriverVerify.java
void notifyVerify() { if (progressBars[0].getProgress() == progressBars[0].getMax() && progressBars[1].getProgress() == progressBars[1].getMax() && progressBars[2].getProgress() == progressBars[2].getMax() && progressBars[3].getProgress() == progressBars[3].getMax()) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("carId", String.valueOf(carId))); Looper.prepare();// w w w.j a v a 2s. c o m // util.doPostRequest String result = HttpUtil.post(params, Constant.URL_CARVERIFICATION, CarDriverVerify.this); if (!util.isNullOrEmpty(result)) { JsonResult<String> Result = util.getObjFromJsonResult(result, new TypeToken<JsonResult<String>>() { }); if (Result.isSuccess()) { Util.showToast(CarDriverVerify.this, getResources().getString(R.string.driver_verify_nofity_upload_success_tips)); } else { Util.showToast(CarDriverVerify.this, Result.getErrorMsg().toString()); } } Looper.loop(); } }
From source file:com.jinrustar.sky.main.MainActivity.java
public void connect() { if (!TextUtils.isEmpty(content)) { AsyncTask<Void, String, Void> read = new AsyncTask<Void, String, Void>() { @Override//from ww w .java2 s .c o m protected Void doInBackground(Void... params) { try { Log.i("connectIP:", content); if (socket == null) socket = new Socket(content, 2016); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); publishProgress("@sucess"); String line; while ((line = reader.readLine()) != null) { publishProgress(line); } } catch (Exception e) { isConnect = false; // Constants._IP = content; e.printStackTrace(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); Toast.makeText(context, "", Toast.LENGTH_SHORT).show(); Looper.loop(); } }).start(); } return null; } @Override protected void onProgressUpdate(String... values) { if (values[0].equals("@sucess")) { isConnect = true; Constants._IP = content; Toast.makeText(context, "?", Toast.LENGTH_SHORT).show(); } if (values[0].contains("http")) { if (downloadid != 400 && downloadVideoInfos != null && downloadVideoInfos.size() > 0) { downloadVideoInfos.get(count - 1).setUrl(values[0]); String url = values[0]; // url = "http://www.x-ways.net/winhex/winhex.zip?t=123212421"; if (url.contains("?")) url = url.split("\\?")[0]; FileDownloader.start(url); Toast.makeText(context, url + "\n??", Toast.LENGTH_SHORT).show(); } } super.onProgressUpdate(values); } }; read.execute(); } }
From source file:github.popeen.dsub.service.DownloadService.java
@Override public void onCreate() { super.onCreate(); final SharedPreferences prefs = Util.getPreferences(this); new Thread(new Runnable() { public void run() { Looper.prepare();//from www. j a v a 2 s . c o m mediaPlayer = new MediaPlayer(); mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK); // We want to change audio session id's between upgrading Android versions. Upgrading to Android 7.0 is broken (probably updated session id format) audioSessionId = -1; int id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1); int versionCode = prefs.getInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, -1); if (versionCode == Build.VERSION.SDK_INT && id != -1) { try { audioSessionId = id; mediaPlayer.setAudioSessionId(audioSessionId); } catch (Throwable e) { Log.w(TAG, "Failed to use cached audio session", e); audioSessionId = -1; } } if (audioSessionId == -1) { mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { audioSessionId = mediaPlayer.getAudioSessionId(); SharedPreferences.Editor editor = prefs.edit(); editor.putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId); editor.putInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, Build.VERSION.SDK_INT); editor.commit(); } catch (Throwable t) { // Froyo or lower } } 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, audioSessionId); i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName()); sendBroadcast(i); } catch(Throwable e) { // Froyo or lower }*/ effectsController = new AudioEffectsController(DownloadService.this, audioSessionId); if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) { getEqualizerController(); } mediaPlayerLooper = Looper.myLooper(); mediaPlayerHandler = new Handler(mediaPlayerLooper); if (runListenersOnInit) { onSongsChanged(); onSongProgress(); onStateUpdate(); } Looper.loop(); } }, "DownloadService").start(); Util.registerMediaButtonEventReceiver(this); audioNoisyReceiver = new AudioNoisyReceiver(); registerReceiver(audioNoisyReceiver, audioNoisyIntent); if (mRemoteControl == null) { // Use the remote control APIs (if available) to set the playback state mRemoteControl = RemoteControlClientBase.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); WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "downloadServiceLock"); 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); mediaRouter = new MediaRouteManager(this); instance = this; shufflePlayBuffer = new ShufflePlayBuffer(this); artistRadioBuffer = new ArtistRadioBuffer(this); lifecycleSupport.onCreate(); if (Build.VERSION.SDK_INT >= 26) { Notifications.shutGoogleUpNotification(this); } }
From source file:uk.org.rivernile.edinburghbustracker.android.Application.java
/** * Download the stop database from the server and put it in the * application's working data directory. * * @param context The context to use this method with. * @param url The URL of the bus stop database to download. *//*from www.j a v a 2 s .co m*/ private static void updateStopsDB(final Context context, final String url, final String checksum) { if (context == null || url == null || url.length() == 0 || checksum == null || checksum.length() == 0) return; try { // Connect to the server. final URL u = new URL(url); final HttpURLConnection con = (HttpURLConnection) u.openConnection(); final InputStream in = con.getInputStream(); // Make sure the URL is what we expect. if (!u.getHost().equals(con.getURL().getHost())) { in.close(); con.disconnect(); return; } // The location the file should be downloaded to. final File temp = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp"); // The eventual destination of the file. final File dest = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME); final FileOutputStream out = new FileOutputStream(temp); // Get the file from the server. byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Make sure the stream is flushed then close resources and // disconnect. out.flush(); out.close(); in.close(); con.disconnect(); // Do a MD5 checksum on the downloaded file. Make sure it matches // what the server reported. if (!md5Checksum(temp).equalsIgnoreCase(checksum)) { // If it doesn't match, delete the downloaded file. temp.delete(); return; } try { // Open the temp database and execute the index operation on it. final SQLiteDatabase db = SQLiteDatabase.openDatabase(temp.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE); BusStopDatabase.setUpIndexes(db); db.close(); } catch (SQLiteException e) { // If we couldn't create the index, continue anyway. The user // will still be able to use the database, it will just run // slowly if they want route lines. } // Close a currently open database. Delete the old database then // move the downloaded file in to its place. Do this while // synchronized to make sure noting else uses the database in this // time. final BusStopDatabase bsd = BusStopDatabase.getInstance(context.getApplicationContext()); synchronized (bsd) { try { bsd.getReadableDatabase().close(); } catch (SQLiteException e) { // Nothing to do here. Assume it's already closed. } dest.delete(); temp.renameTo(dest); } // Delete the associated journal file because we no longer need it. final File journalFile = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp-journal"); if (journalFile.exists()) journalFile.delete(); // Alert the user that the database has been updated. Looper.prepare(); Toast.makeText(context, R.string.bus_stop_db_updated, Toast.LENGTH_LONG).show(); Looper.loop(); } catch (MalformedURLException e) { } catch (IOException e) { } }