List of usage examples for android.os HandlerThread HandlerThread
public HandlerThread(String name)
From source file:pct.droid.base.torrent.TorrentService.java
/** * Initialize will setup the thread and handler, * and start/resume the torrent session// w ww . j a v a 2 s . c o m */ private void initialize() { if (mInForeground) { stopForeground(); } Timber.d("initialize"); if (mThread != null) { mHandler.removeCallbacksAndMessages(null); //resume torrent session if needed if (mTorrentSession != null && mTorrentSession.isPaused()) { mHandler.post(new Runnable() { @Override public void run() { Timber.d("Resuming libtorrent session"); mTorrentSession.resume(); } }); } //start DHT if needed if (mDHT != null && !mDHT.isRunning()) { mHandler.post(new Runnable() { @Override public void run() { mDHT.start(); Timber.d("Nodes in DHT: %s", mDHT.nodes()); } }); } } else { if (mInitialised) return; mThread = new HandlerThread(THREAD_NAME); mThread.start(); mHandler = new Handler(mThread.getLooper()); mHandler.post(new Runnable() { @Override public void run() { // Start libtorrent session and init DHT Timber.d("Starting libtorrent session"); mTorrentSession = new Session(); SessionSettings sessionSettings = mTorrentSession.getSettings(); sessionSettings.setAnonymousMode(true); mTorrentSession.setSettings(sessionSettings); Timber.d("Init DHT"); mDHT = new DHT(mTorrentSession); mDHT.start(); Timber.d("Nodes in DHT: %s", mDHT.nodes()); mInitialised = true; } }); } }
From source file:com.csipsimple.utils.ContactsAsyncHelper.java
/** * Private constructor for static class//from www . ja v a 2 s. c o m */ private ContactsAsyncHelper() { HandlerThread thread = new HandlerThread("ContactsAsyncWorker"); thread.start(); sThreadHandler = new WorkerHandler(thread.getLooper()); contactsWrapper = ContactsWrapper.getInstance(); }
From source file:com.smithdtyler.prettygoodmusicplayer.MusicPlaybackService.java
@Override public synchronized void onCreate() { Log.i(TAG, "Music Playback Service Created!"); isRunning = true;/*from w ww. j av a 2 s . com*/ sharedPref = PreferenceManager.getDefaultSharedPreferences(this); powerManager = (PowerManager) getSystemService(POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PGMPWakeLock"); random = new Random(); mp = new MediaPlayer(); mReadaheadThread = new ReadaheadThread(); mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Log.i(TAG, "Song complete"); next(); } }); // https://developer.android.com/training/managing-audio/audio-focus.html audioFocusListener = new PrettyGoodAudioFocusChangeListener(); // Get permission to play audio am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE); HandlerThread thread = new HandlerThread("ServiceStartArguments"); thread.start(); // Get the HandlerThread's Looper and use it for our Handler mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); // https://stackoverflow.com/questions/19474116/the-constructor-notification-is-deprecated // https://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly/15538209#15538209 Intent resultIntent = new Intent(this, NowPlaying.class); resultIntent.putExtra("From_Notification", true); resultIntent.putExtra(AlbumList.ALBUM_NAME, album); resultIntent.putExtra(ArtistList.ARTIST_NAME, artist); resultIntent.putExtra(ArtistList.ARTIST_ABS_PATH_NAME, artistAbsPath); // Use the FLAG_ACTIVITY_CLEAR_TOP to prevent launching a second // NowPlaying if one already exists. resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0); Builder builder = new NotificationCompat.Builder(this.getApplicationContext()); String contentText = getResources().getString(R.string.ticker_text); if (songFile != null) { contentText = Utils.getPrettySongName(songFile); } Notification notification = builder.setContentText(contentText).setSmallIcon(R.drawable.ic_pgmp_launcher) .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent) .setContentTitle(getResources().getString(R.string.notification_title)).build(); startForeground(uniqueid, notification); timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { onTimerTick(); } }, 0, 500L); Log.i(TAG, "Registering event receiver"); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // Apparently audio registration is persistent across lots of things... // restarts, installs, etc. mAudioManager.registerMediaButtonEventReceiver(cn); // I tried to register this in the manifest, but it doesn't seen to // accept it, so I'll do it this way. getApplicationContext().registerReceiver(receiver, filter); headphoneReceiver = new HeadphoneBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.HEADSET_PLUG"); registerReceiver(headphoneReceiver, filter); }
From source file:com.wbtech.ums.UmsAgent.java
public static void onEvent(Context context, String event_id, int acc) { if (handler == null) { HandlerThread localHandlerThread = new HandlerThread("UmsAgent"); localHandlerThread.start();//w ww . j a v a 2 s . co m handler = new Handler(localHandlerThread.getLooper()); } EventController.postEventInfo(handler, context, new PostObjEvent(event_id, null, acc + "", context)); }
From source file:de.dcja.prettygreatmusicplayer.MusicPlaybackService.java
@Override public synchronized void onCreate() { Log.i(TAG, "Music Playback Service Created!"); isRunning = true;/*w w w. ja v a 2 s.c o m*/ sharedPref = PreferenceManager.getDefaultSharedPreferences(this); powerManager = (PowerManager) getSystemService(POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PGMPWakeLock"); random = new Random(); mp = new MediaPlayer(); mReadaheadThread = new ReadaheadThread(); mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Log.i(TAG, "Song complete"); next(); } }); onDemandMediaMetadataRetriever = new OnDemandMediaMetadataRetriever(); // https://developer.android.com/training/managing-audio/audio-focus.html audioFocusListener = new PrettyGoodAudioFocusChangeListener(); // Get permission to play audio am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE); HandlerThread thread = new HandlerThread("ServiceStartArguments"); thread.start(); // Get the HandlerThread's Looper and use it for our Handler mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); // https://stackoverflow.com/questions/19474116/the-constructor-notification-is-deprecated // https://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly/15538209#15538209 Intent resultIntent = new Intent(this, NowPlaying.class); resultIntent.putExtra("From_Notification", true); // Use the FLAG_ACTIVITY_CLEAR_TOP to prevent launching a second // NowPlaying if one already exists. resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0); Builder builder = new NotificationCompat.Builder(this.getApplicationContext()); String contentText = getResources().getString(R.string.ticker_text); if (songFile != null) { contentText = Utils.getPrettySongName(songFile); } Notification notification = builder.setContentText(contentText).setSmallIcon(R.drawable.ic_pgmp_launcher) .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent) .setContentTitle(getResources().getString(R.string.notification_title)).build(); startForeground(uniqueid, notification); timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { onTimerTick(); } }, 0, 500L); Log.i(TAG, "Registering event receiver"); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // Apparently audio registration is persistent across lots of things... // restarts, installs, etc. mAudioManager.registerMediaButtonEventReceiver(cn); // I tried to register this in the manifest, but it doesn't seen to // accept it, so I'll do it this way. getApplicationContext().registerReceiver(receiver, filter); headphoneReceiver = new HeadphoneBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.HEADSET_PLUG"); registerReceiver(headphoneReceiver, filter); }
From source file:com.mobicage.rpc.http.HttpCommunicator.java
public HttpCommunicator(final MainService mainService, final Context context, final DatabaseManager databaseManager, final Credentials credentials, final ConfigurationProvider cfgProvider, final SafeRunnable onStartStashingHandler, final SafeRunnable onStopStashingHandler, final SDCardLogger sdcardLogger, final boolean wifiOnlySettingEnabled) { T.UI();//w ww. j a va2 s . c o m mMainService = mainService; mCfgProvider = cfgProvider; mFinishedLock = new Object(); mStateMachineLock = new Object(); mStartStashingHandler = onStartStashingHandler; mStopStashingHandler = onStopStashingHandler; mWifiOnlyEnabled = wifiOnlySettingEnabled; mSDCardLogger = sdcardLogger; mAlarmManager = (AlarmManager) mMainService.getSystemService(Context.ALARM_SERVICE); // Create network thread for actual network communication mNetworkWorkerThread = new HandlerThread("rogerthat_net_worker"); mNetworkWorkerThread.start(); final Looper looper = mNetworkWorkerThread.getLooper(); mNetworkHandler = new Handler(looper); mNetworkHandler.post(new SafeRunnable() { @Override protected void safeRun() throws Exception { debugLog("HTTP network thread id is " + android.os.Process.myTid()); } }); final CountDownLatch latch = new CountDownLatch(1); mMainService.postAtFrontOfBIZZHandler(new SafeRunnable() { @Override public void safeRun() { T.BIZZ(); // For simplicity, I want to construct backlog on HTTP thread // This way backlog is 100% on HTTP thread mBacklog = new HttpBacklog(context, databaseManager); latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { bugLog(e); } mBase64Username = Base64.encodeBytes(credentials.getUsername().getBytes(), Base64.DONT_BREAK_LINES); mBase64Password = Base64.encodeBytes(credentials.getPassword().getBytes(), Base64.DONT_BREAK_LINES); mMainService.addHighPriorityIntent(HttpCommunicator.INTENT_HTTP_START_OUTGOING_CALLS); if (CloudConstants.USE_GCM_KICK_CHANNEL) { final IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); filter.addAction(INTENT_SHOULD_RETRY_COMMUNICATION); mMainService.registerReceiver(mBroadcastReceiver, filter); } }
From source file:com.tafayor.selfcamerashot.taflib.iab.util.IabHelper.java
/** * Creates an instance. After creation, it will not yet be ready to use. You must perform * setup by calling {@link #startSetup} and wait for setup to complete. This constructor does not * block and is safe to call from a UI thread. * * @param ctx Your application or Activity context. Needed to bind to the in-app billing service. * @param base64PublicKey Your application's public key, encoded in base64. * This is used for verification of purchase signatures. You can find your app's base64-encoded * public key in your application's page on Google Play Developer Console. Note that this * is NOT your "developer public key". */// w w w . j a v a 2s. com public IabHelper(Context ctx, String base64PublicKey) { mContext = ctx.getApplicationContext(); mSignatureBase64 = base64PublicKey; logDebug("IAB helper created."); mThread = new HandlerThread(""); mThread.start(); mAsyncHandler = new Handler(mThread.getLooper()); }
From source file:uk.co.pjmobile.mobile_apps.page_turner_reader.ReadingActivity.java
/** Called when the activity is first created. */ @Override//from w ww . jav a 2s .c om public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Restore preferences requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.read_book); setupConstants(); this.uiHandler = new Handler(); HandlerThread bgThread = new HandlerThread("background"); bgThread.start(); this.backgroundHandler = new Handler(bgThread.getLooper()); this.waitDialog = new ProgressDialog(this); this.waitDialog.setOwnerActivity(this); this.waitDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // This just consumes all key events and does nothing. return true; } }); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); this.gestureDetector = new GestureDetector(this, new NavGestureDetector(bookView, this, metrics)); // this.gestureDetector = new GestureDetector(new NavGestureDetector( //bookView, this, metrics)); this.gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }; this.progressBar.setFocusable(true); this.progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { private int seekValue; @Override public void onStopTrackingTouch(SeekBar seekBar) { bookView.navigateToPercentage(this.seekValue); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { seekValue = progress; percentageField.setText(progress + "% "); } } }); this.viewSwitcher.setOnTouchListener(gestureListener); bookView.setOnTouchListener(gestureListener); bookView.addListener(this); bookView.setSpanner(getInjector().getInstance(HtmlSpanner.class)); // this.bookView.setSpanner(new HtmlSpanner()); this.oldBrightness = config.isBrightnessControlEnabled(); this.oldStripWhiteSpace = config.isStripWhiteSpaceEnabled(); this.oldFontName = config.getFontFamily().getName(); registerForContextMenu(bookView); String file = getIntent().getStringExtra("file_name"); if (file == null && getIntent().getData() != null) { file = getIntent().getData().getPath(); } if (file == null) { file = config.getLastOpenedFile(); } updateFromPrefs(); updateFileName(savedInstanceState, file); if ("".equals(fileName)) { // Intent intent = new Intent(this, LibraryActivity.class); // startActivity(intent); // finish(); // return; // Util.toast(this, "Launch library activity. Empty file name"); } else { /** if (savedInstanceState == null && config.isSyncEnabled()) { new DownloadProgressTask().execute(); } else {**/ bookView.restore(); // } } }
From source file:com.ubergeek42.WeechatAndroid.service.RelayServiceBackbone.java
@Override public void onCreate() { if (DEBUG)/*from ww w . ja v a2s . c o m*/ logger.debug("onCreate()"); super.onCreate(); prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); prefs.registerOnSharedPreferenceChangeListener(this); notificationManger = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // prepare handler that will run on a separate thread HandlerThread handler_thread = new HandlerThread("doge"); handler_thread.start(); thandler = new Handler(handler_thread.getLooper()); startForeground(NOTIFICATION_ID, buildNotification(null, "Tap to connect", null)); disconnected = false; already_had_intent = false; network_unavailable = false; // Prepare for dealing with SSL certs certmanager = new SSLHandler(new File(getDir("sslDir", Context.MODE_PRIVATE), "keystore.jks")); registerReceiver(connectivityActionReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); }
From source file:com.waz.zclient.pages.main.conversation.LocationFragment.java
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (isGooglePlayServicesAvailable()) { googleApiClient = new GoogleApiClient.Builder(getContext()).addConnectionCallbacks(this) .addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); } else {/* w w w .j a va 2s.c om*/ locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); } mainHandler = new Handler(); handlerThread = new HandlerThread("Background handler"); handlerThread.start(); backgroundHandler = new Handler(handlerThread.getLooper()); geocoder = new Geocoder(getContext(), Locale.getDefault()); zoom = true; }