List of usage examples for android.os Looper prepare
public static void prepare()
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(); mediaPlayer = new MediaPlayer(); mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK); audioSessionId = -1;// ww w . j a v a2 s . c om 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:eu.dirtyharry.androidopsiadmin.Main.java
public void buttonListener(final View view) { if (vibrate) { view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); }/* www . j ava 2s . c o m*/ // new Functions().noPreferences(Main.this, // getString(R.string.gen_title_error), // getString(R.string.gen_setpreferences)); if (!new Functions().checkPreferences(Main.this)) { new Functions().noPreferences(Main.this, getString(R.string.gen_title_error), getString(R.string.gen_setserverpreferences)); return; } // noPreferences(Main.this, // getString(R.string.gen_title_error), // getString(R.string.gen_setpreferences)); switch (view.getId()) { case R.id.bt_scanqr: // Intent intent = new // Intent("com.google.zxing.client.android.SCAN"); // intent.setPackage("com.google.zxing.client.android"); // intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // setResult(RESULT_OK, intent); // startActivityForResult(intent, 0); Intent qrDroid = new Intent("la.droid.qr.scan"); qrDroid.putExtra("la.droid.qr.complete", true); try { startActivityForResult(qrDroid, GET_QR); } catch (ActivityNotFoundException activity) { Functions.qrDroidRequired(Main.this); } break; case R.id.bt_getopsiclients: Log.d("Barcode", "getopsiclient"); // if (Networking.isConnected(Main.this)) { getOpsiClientsTask(); // } else { // Toast.makeText(Main.this, R.string.to_wifinotconnected, // Toast.LENGTH_LONG).show(); // } break; case R.id.bt_defineclientselection: if (Networking.isConnected(Main.this)) { final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait), getString(R.string.pd_getclients), true); final Handler handler = new Handler() { public void handleMessage(Message msg) { dialog.dismiss(); if (GlobalVar.getInstance().getError().equals("null")) { if (doit.equals("serverdown")) { Toast.makeText(Main.this, String.format(getString(R.string.to_servernotrechable), serverip), Toast.LENGTH_LONG).show(); } } else { new Functions().msgBox(Main.this, getString(R.string.gen_title_error), GlobalVar.getInstance().getError(), false); } } }; Thread checkUpdate = new Thread() { public void run() { Looper.prepare(); if (Networking.isServerUp(serverip, serverport, serverusername, serverpasswd)) { doit = "true"; Intent i = new Intent(Main.this, ShowOpsiClientFilter.class); startActivity(i); } else { doit = "serverdown"; } handler.sendEmptyMessage(0); } }; checkUpdate.start(); } else { Toast.makeText(Main.this, R.string.to_wifinotconnected, Toast.LENGTH_LONG).show(); } break; case R.id.bt_createopsiclient: // new Functions().notImplementet(Main.this); Intent i = new Intent(Main.this, ShowOpsiCreateClient.class); startActivity(i); break; case R.id.bt_showdepotconfig: // new Functions().notImplementet(Main.this); Log.d("Barcode", "depotconfig"); if (Networking.isConnected(Main.this)) { getOPSIDepots(); } else { Toast.makeText(Main.this, R.string.to_wifinotconnected, Toast.LENGTH_LONG).show(); } break; // case R.id.bt_test: // ArrayList<String> test = new ArrayList<String>(); // test.add("test1"); // test.add("test2"); // test.add("test3"); // test.add("test4"); // ShowOpsiClientOptionsButtonDialog buttondialog = new // ShowOpsiClientOptionsButtonDialog(Main.this,test); // buttondialog.setTitle("testtitle"); // buttondialog.show(); // break; } }
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 *//*w ww .j ava2 s .com*/ 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 *///from ww w . j a v a 2 s . co 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:com.google.sample.cast.refplayer.Synchronization.java
public void buildSocketConnection() { Thread socket = new Thread("Client") { private Socket clientSocket; BufferedInputStream in;//from w ww.j a v a 2 s . co 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: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(); 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;/*from ww w.j a v a 2 s .c o m*/ 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:com.smallzhi.autobahn.WebSocketConnection.java
/** * Create master message handler.// ww w . j a v a 2 s . c om */ protected void createHandler() { try { if (Looper.myLooper() != null) { return; } Looper.prepare(); mMasterHandler = new Handler(Looper.myLooper()) { public void handleMessage(Message msg) { if (msg.obj instanceof WebSocketMessage.TextMessage) { WebSocketMessage.TextMessage textMessage = (WebSocketMessage.TextMessage) msg.obj; if (mWsHandler != null) { mWsHandler.onTextMessage(textMessage.mPayload); } else { if (DEBUG) Log.d(TAG, "could not call onTextMessage() .. handler already NULL"); } } else if (msg.obj instanceof WebSocketMessage.RawTextMessage) { WebSocketMessage.RawTextMessage rawTextMessage = (WebSocketMessage.RawTextMessage) msg.obj; if (mWsHandler != null) { mWsHandler.onRawTextMessage(rawTextMessage.mPayload); } else { if (DEBUG) Log.d(TAG, "could not call onRawTextMessage() .. handler already NULL"); } } else if (msg.obj instanceof WebSocketMessage.BinaryMessage) { WebSocketMessage.BinaryMessage binaryMessage = (WebSocketMessage.BinaryMessage) msg.obj; if (mWsHandler != null) { mWsHandler.onBinaryMessage(binaryMessage.mPayload); } else { if (DEBUG) Log.d(TAG, "could not call onBinaryMessage() .. handler already NULL"); } } else if (msg.obj instanceof WebSocketMessage.Ping) { WebSocketMessage.Ping ping = (WebSocketMessage.Ping) msg.obj; if (DEBUG) Log.d(TAG, "WebSockets Ping received"); // reply with Pong WebSocketMessage.Pong pong = new WebSocketMessage.Pong(); pong.mPayload = ping.mPayload; mWriter.forward(pong); } else if (msg.obj instanceof WebSocketMessage.Pong) { @SuppressWarnings("unused") WebSocketMessage.Pong pong = (WebSocketMessage.Pong) msg.obj; if (DEBUG) Log.d(TAG, "WebSockets Pong received"); } else if (msg.obj instanceof WebSocketMessage.Close) { WebSocketMessage.Close close = (WebSocketMessage.Close) msg.obj; if (DEBUG) Log.d(TAG, "WebSockets Close received (" + close.mCode + " - " + close.mReason + ")"); mWriter.forward(new WebSocketMessage.Close(1000)); } else if (msg.obj instanceof WebSocketMessage.ServerHandshake) { WebSocketMessage.ServerHandshake serverHandshake = (WebSocketMessage.ServerHandshake) msg.obj; if (DEBUG) Log.d(TAG, "opening handshake received"); if (serverHandshake.mSuccess) { if (mWsHandler != null) { mWsHandler.onOpen(); } else { if (DEBUG) Log.d(TAG, "could not call onOpen() .. handler already NULL"); } } } else if (msg.obj instanceof WebSocketMessage.ConnectionLost) { @SuppressWarnings("unused") WebSocketMessage.ConnectionLost connnectionLost = (WebSocketMessage.ConnectionLost) msg.obj; failConnection(WebSocketConnectionHandler.CLOSE_CONNECTION_LOST, "WebSockets connection lost"); } else if (msg.obj instanceof WebSocketMessage.ProtocolViolation) { @SuppressWarnings("unused") WebSocketMessage.ProtocolViolation protocolViolation = (WebSocketMessage.ProtocolViolation) msg.obj; failConnection(WebSocketConnectionHandler.CLOSE_PROTOCOL_ERROR, "WebSockets protocol violation"); } else if (msg.obj instanceof WebSocketMessage.Error) { WebSocketMessage.Error error = (WebSocketMessage.Error) msg.obj; failConnection(WebSocketConnectionHandler.CLOSE_INTERNAL_ERROR, "WebSockets internal error (" + error.mException.toString() + ")"); } else if (msg.obj instanceof WebSocketMessage.ServerError) { WebSocketMessage.ServerError error = (WebSocketMessage.ServerError) msg.obj; failConnection(WebSocketConnectionHandler.CLOSE_SERVER_ERROR, "Server error " + error.mStatusCode + " (" + error.mStatusMessage + ")"); } else { processAppMessage(msg.obj); } } }; } catch (Exception e) { Log.d(TAG, "createHandler fail:==>>" + e.toString()); } }
From source file:fi.mikuz.boarder.gui.DropboxMenu.java
public void initializeTransfer(final ArrayList<String> boards, final boolean cleanUnusedFiles) { mWaitDialog = new ProgressDialog(this); mWaitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mWaitDialog.setMessage("Please wait"); mWaitDialog.show();// w w w .j av a 2 s.co m t = new Thread() { public void run() { Looper.prepare(); DropboxAPI.Account account = null; try { account = mApi.accountInfo(); } catch (DropboxException e) { Log.e(TAG, "Account info missing", e); } if (account != null) { if (mOperation == UPLOAD_OPERATION) { upload(boards, cleanUnusedFiles); } else if (mOperation == DOWNLOAD_OPERATION) { download(boards, cleanUnusedFiles); } } else { mWaitDialog.dismiss(); } } }; t.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(); // 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>>() { });/* w ww . jav a2 s. c om*/ 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/* w ww. j a va2 s . co 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(); } }