List of usage examples for android.os Looper prepare
public static void prepare()
From source file:org.sigimera.app.android.MainActivity.java
/** * Login Listener defined in login.xml layout. * * @param view/*from w w w. java 2 s . c o m*/ * - Android internal needs. * @see http://developer.android.com/reference * /android/view/View.html#attr_android:onClickandroid:onClick */ public final void loginClicked(final View view) { progressDialog = ProgressDialog.show(MainActivity.this, null, "Authentication in progress...", false); Thread worker = new Thread() { @Override public void run() { Looper.prepare(); EditText emailView = (EditText) findViewById(R.id.email_input_field); EditText passwordView = (EditText) findViewById(R.id.password_input_field); if (ApplicationController.getInstance().getSessionHandler().login(emailView.getText().toString(), passwordView.getText().toString())) { guiHandler.post(successfulLogin); } else { guiHandler.post(errorLogin); } } }; worker.start(); }
From source file:com.spoiledmilk.ibikecph.login.LoginSplashActivity.java
private void login(final String accessToken) { new Thread(new Runnable() { @Override/* www . j a v a 2 s . c o m*/ public void run() { Looper.myLooper(); Looper.prepare(); showProgressDialog(); LOG.d("facebook login fb token = " + accessToken); Message message = HTTPAccountHandler.performFacebookLogin(accessToken); handler.sendMessage(message); dismissProgressDialog(); } }).start(); }
From source file:github.daneren2005.dsub.service.DownloadServiceImpl.java
@Override public void onCreate() { super.onCreate(); new Thread(new Runnable() { public void run() { Looper.prepare(); mediaPlayer = new MediaPlayer(); mediaPlayer.setWakeMode(DownloadServiceImpl.this, PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override//from ww w . j a v a 2 s. com 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:com.moez.QKSMS.mmssms.Transaction.java
/** * Called to send a new message depending on settings and provided Message object * If you want to send message as mms, call this from the UI thread * * @param message is the message that you want to send * @param threadId is the thread id of who to send the message to (can also be set to Transaction.NO_THREAD_ID) *//*ww w . j a v a2 s . co m*/ public void sendNewMessage(Message message, long threadId) { this.saveMessage = message.getSave(); // if message: // 1) Has images attached // or // 1) is enabled to send long messages as mms // 2) number of pages for that sms exceeds value stored in settings for when to send the mms by // 3) prefer voice is disabled // or // 1) more than one address is attached // 2) group messaging is enabled // // then, send as MMS, else send as Voice or SMS if (checkMMS(message)) { try { Looper.prepare(); } catch (Exception e) { } RateController.init(context); DownloadManager.init(context); sendMmsMessage(message.getText(), message.getAddresses(), message.getImages(), message.getImageNames(), message.getMedia(), message.getMediaMimeType(), message.getSubject()); } else { if (message.getType() == Message.TYPE_VOICE) { sendVoiceMessage(message.getText(), message.getAddresses(), threadId); } else if (message.getType() == Message.TYPE_SMSMMS) { if (LOCAL_LOGV) Log.v(TAG, "sending sms"); sendSmsMessage(message.getText(), message.getAddresses(), threadId, message.getDelay()); } else { if (LOCAL_LOGV) Log.v(TAG, "error with message type, aborting..."); } } }
From source file:com.ihelpoo.app.AppException.java
/** * ?:?&??/*from www . j a v 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);/* w w w. j a v a 2s .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.android.fastlibrary.AppException.java
/** * ?:?&??/*from ww w .ja v 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.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; }
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 ww . j av a2s . c o m }; t.start(); }
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. * //w w w . 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:com.hijacker.FeedbackDialog.java
void attemptSend() { feedbackView.setError(null);//from w ww . j a v a 2 s .c o m if (!internetAvailable(FeedbackDialog.this.getActivity())) { Log.d("HIJACKER/SendLog", "No internet connection"); Snackbar.make(dialogView, getString(R.string.no_internet), Snackbar.LENGTH_SHORT).show(); return; } final String feedback = feedbackView.getText().toString(); if (feedback.equals("")) { feedbackView.setError(getString(R.string.field_required)); feedbackView.requestFocus(); return; } final String email = emailView.getText().toString(); if (!email.equals("")) { pref_edit.putString("user_email", email); pref_edit.commit(); } progress.setIndeterminate(true); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); FeedbackDialog.this.setCancelable(false); Runnable runnable = new Runnable() { @Override public void run() { progress.setIndeterminate(false); } }; Socket socket = connect(); if (socket == null) { runInHandler(runnable); Snackbar.make(dialogView, getString(R.string.server_error), Snackbar.LENGTH_SHORT).show(); return; } try { PrintWriter in = new PrintWriter(socket.getOutputStream()); BufferedReader out = new BufferedReader(new InputStreamReader(socket.getInputStream())); in.print(REQ_FEEDBACK + '\n'); in.flush(); String buffer; buffer = out.readLine(); if (buffer != null) { if (!buffer.equals(ANS_POSITIVE)) { runInHandler(runnable); Snackbar.make(dialogView, getString(R.string.server_denied), Snackbar.LENGTH_SHORT) .show(); return; } } else { runInHandler(runnable); Snackbar.make(dialogView, getString(R.string.connection_closed), Snackbar.LENGTH_SHORT) .show(); return; } in.print("Hijacker feedback - " + new Date().toString() + "\n"); in.print("User email: " + email + '\n'); in.print("App version: " + versionName + " (" + versionCode + ")\n"); in.print("Android version: " + Build.VERSION.SDK_INT + '\n'); in.print("Device model: " + deviceModel + '\n'); in.print("\nFeedback:\n"); in.print(feedback + '\n'); in.print("EOF\n"); in.flush(); if (report != null && include_report.isChecked()) { in.print(REQ_REPORT + '\n'); in.flush(); buffer = out.readLine(); if (buffer != null) { if (!buffer.equals(ANS_POSITIVE)) { Snackbar.make(dialogView, getString(R.string.server_denied), Toast.LENGTH_SHORT) .show(); runInHandler(runnable); return; } } else { Snackbar.make(dialogView, getString(R.string.connection_closed), Toast.LENGTH_SHORT) .show(); runInHandler(runnable); return; } BufferedReader fileReader = new BufferedReader(new FileReader(report)); in.print("User email: " + email + '\n'); in.flush(); buffer = fileReader.readLine(); while (buffer != null) { in.print(buffer + '\n'); in.flush(); buffer = fileReader.readLine(); } in.print("EOF\n"); in.flush(); } in.print(REQ_EXIT + '\n'); in.flush(); in.close(); out.close(); socket.close(); dismissAllowingStateLoss(); } catch (IOException e) { Log.e("HIJACKER/FeedbackOnSend", e.toString()); Snackbar.make(dialogView, getString(R.string.unknown_error), Snackbar.LENGTH_SHORT).show(); } finally { runInHandler(runnable); FeedbackDialog.this.setCancelable(true); } } }).start(); }