List of usage examples for android.os HandlerThread HandlerThread
public HandlerThread(String name, int priority)
From source file:edu.utexas.quietplaces.mocklocations.SendMockLocationService.java
@Override public void onCreate() { /*/*from w w w . j a v a 2 s .co m*/ * Load the mock location data from MockLocationConstants.java */ LocationArray testData = getTestDataFromFile(); if (testData != null) { mLocationArray = buildTestLocationArray(testData.lat_list, testData.lng_list, testData.accuracy_list); } /* * Prepare to send status updates back to the main activity. * Get a local broadcast manager instance; broadcast intents sent via this * manager are only available within the this app. */ mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); /* * Create a new background thread with an associated Looper that processes Message objects * from a MessageQueue. The Looper allows test Activities to send repeated requests to * inject mock locations from this Service. */ mWorkThread = new HandlerThread("UpdateThread", Process.THREAD_PRIORITY_BACKGROUND); /* * Start the thread. Nothing actually runs until the Looper for this thread dispatches a * Message to the Handler. */ mWorkThread.start(); // Get the Looper for the thread mUpdateLooper = mWorkThread.getLooper(); /* * Create a Handler object and pass in the Looper for the thread. * The Looper can now dispatch Message objects to the Handler's handleMessage() method. */ mUpdateHandler = new UpdateHandler(mUpdateLooper); // Indicate that testing has not yet started mTestStarted = false; }
From source file:com.socialdisasters.other.service.ChatService.java
@Override public void onCreate() { // call onCreate of the super-class super.onCreate(); // create a roster object this.roster = new Roster(); this.roster.open(this); // create a new background looper mUpdateThread = new HandlerThread(TAG, android.os.Process.THREAD_PRIORITY_BACKGROUND); mUpdateThread.start();//from www .j a va 2 s . co m Looper looper = mUpdateThread.getLooper(); mUpdateHandler = new UpdateHandler(looper, roster); // create registration Registration registration = new Registration("chat"); registration.add(PRESENCE_GROUP_EID); try { initialize(registration); _service_error = ServiceError.NO_ERROR; } catch (ServiceNotAvailableException e) { _service_error = ServiceError.SERVICE_NOT_FOUND; } catch (SecurityException ex) { _service_error = ServiceError.PERMISSION_NOT_GRANTED; } // register to presence changes SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.registerOnSharedPreferenceChangeListener(mPrefListener); // schedule update actions for all online buddies Cursor c = getRoster().queryOnlineBuddies(); RosterAdapter.ColumnsMap cmap = new RosterAdapter.ColumnsMap(); while (c.moveToNext()) { Buddy b = new Buddy(this, c, cmap); // obtain a new refresh message android.os.Message msg = mUpdateHandler.obtainMessage(REFRESH_BUDDY_DATA, b.getEndpoint()); // schedule the update in 61 minutes mUpdateHandler.sendMessageDelayed(msg, 61 * 60 * 1000); Log.d(TAG, "scheduled update for " + b.getEndpoint()); } Log.i(TAG, "service created."); }
From source file:edu.berkeley.eecs.cfc_tracker.test.location.SendMockLocationService.java
public void onCreate(Context ctxt) { /*/*from w w w.j a v a 2s.co m*/ * Load the mock location data from MockLocationConstants.java */ mLocationArray = buildTestLocationArray(LocationUtils.WAYPOINTS_LAT, LocationUtils.WAYPOINTS_LNG, LocationUtils.WAYPOINTS_ACCURACY); /* * Prepare to send status updates back to the main activity. * Get a local broadcast manager instance; broadcast intents sent via this * manager are only available within the this app. */ mLocalBroadcastManager = LocalBroadcastManager.getInstance(ctxt); /* * Create a new background thread with an associated Looper that processes Message objects * from a MessageQueue. The Looper allows test Activities to send repeated requests to * inject mock locations from this Service. */ mWorkThread = new HandlerThread("UpdateThread", Process.THREAD_PRIORITY_BACKGROUND); /* * Start the thread. Nothing actually runs until the Looper for this thread dispatches a * Message to the Handler. */ mWorkThread.start(); // Get the Looper for the thread mUpdateLooper = mWorkThread.getLooper(); /* * Create a Handler object and pass in the Looper for the thread. * The Looper can now dispatch Message objects to the Handler's handleMessage() method. */ mUpdateHandler = new UpdateHandler(mUpdateLooper); // Create a location client mGoogleApiClient = new GoogleApiClient.Builder(ctxt).addConnectionCallbacks(this) .addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); // Indicate that testing has not yet started mTestStarted = false; }
From source file:com.sidekickApp.analytics.LocalyticsSession.java
/** * Helper to obtain a new {@link HandlerThread}. * * @param name to give to the HandlerThread. Useful for debugging, as the thread name is shown in DDMS. * @return HandlerThread whose {@link HandlerThread#start()} method has already been called. */// w w w.j a v a 2 s. c o m private static HandlerThread getHandlerThread(final String name) { final HandlerThread thread = new HandlerThread(name, android.os.Process.THREAD_PRIORITY_BACKGROUND); thread.start(); /* * Note: we tried setting an uncaught exception handler here. But for some reason it causes looper initialization to fail * randomly. */ return thread; }
From source file:com.koma.music.service.MusicService.java
/** * {@inheritDoc}//from w w w . j a va 2 s . c o m */ @Override public void onCreate() { LogUtils.d(TAG, "Creating service"); super.onCreate(); if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { stopSelf(); return; } else { mReadGranted = true; } mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Initialize the favorites and recents databases mRecentlyPlayCache = RecentlyPlay.getInstance(this); // gets the song play count cache mSongPlayCountCache = SongPlayCount.getInstance(this); // gets a pointer to the playback state store mPlaybackStateStore = MusicPlaybackState.getInstance(this); // Initialize the image fetcher // mImageFetcher = ImageFetcher.getInstance(this); // Initialize the image cache // mImageFetcher.setImageCache(ImageCache.getInstance(this)); // Start up the thread running the service. Note that we create a // separate thread because the service normally runs in the process's // main thread, which we don't want to block. We also make it // background priority so CPU-intensive work will not disrupt the UI. mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND); mHandlerThread.start(); // Initialize the handler mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper()); // Initialize the audio manager and register any headset controls for // playback mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // Use the remote control APIs to set the playback state setUpMediaSession(); // Initialize the preferences mPreferences = getSharedPreferences("MusicService", 0); mCardId = getCardId(); mShowAlbumArtOnLockscreen = mPreferences.getBoolean(PreferenceUtils.SHOW_ALBUM_ART_ON_LOCKSCREEN, false); setShakeToPlayEnabled(mPreferences.getBoolean(PreferenceUtils.SHAKE_TO_PLAY, false)); registerExternalStorageListener(); // Initialize the media player mPlayer = new MultiPlayer(this); mPlayer.setHandler(mPlayerHandler); // Initialize the intent filter and each action final IntentFilter filter = new IntentFilter(); filter.addAction(MusicServiceConstants.SERVICECMD); filter.addAction(MusicServiceConstants.TOGGLEPAUSE_ACTION); filter.addAction(MusicServiceConstants.PAUSE_ACTION); filter.addAction(MusicServiceConstants.STOP_ACTION); filter.addAction(MusicServiceConstants.NEXT_ACTION); filter.addAction(MusicServiceConstants.PREVIOUS_ACTION); filter.addAction(MusicServiceConstants.PREVIOUS_FORCE_ACTION); filter.addAction(MusicServiceConstants.REPEAT_ACTION); filter.addAction(MusicServiceConstants.SHUFFLE_ACTION); // Attach the broadcast listener registerReceiver(mIntentReceiver, filter); // Get events when MediaStore content changes mMediaObserver = new MediaObserver(mPlayerHandler); getContentResolver().registerContentObserver(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true, mMediaObserver); getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mMediaObserver); // Initialize the delayed shutdown intent final Intent shutdownIntent = new Intent(this, MusicService.class); shutdownIntent.setAction(MusicServiceConstants.SHUTDOWN); mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0); // Listen for the idle state scheduleDelayedShutdown(); // Bring the queue back reloadQueue(); notifyChange(MusicServiceConstants.QUEUE_CHANGED); notifyChange(META_CHANGED); }
From source file:hashengineering.digitalcoin.wallet.ui.SendCoinsFragment.java
@Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true);/*from w w w .j a va 2 s.c om*/ bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND); backgroundThread.start(); backgroundHandler = new Handler(backgroundThread.getLooper()); btcPrecision = Integer.parseInt( prefs.getString(Constants.PREFS_KEY_BTC_PRECISION, Constants.PREFS_DEFAULT_BTC_PRECISION)); }
From source file:com.example.locationprovider.app.SendMockLocationService.java
@Override public void onCreate() { /*/*from w w w . j a v a 2 s.c om*/ * Load the mock location data from MockLocationConstants.java */ // mLocationArray = buildTestLocationArray(LocationUtils.WAYPOINTS_LAT, LocationUtils.WAYPOINTS_LNG, LocationUtils.WAYPOINTS_ACCURACY); mLocationArray = buildTestLocationArray(); /* * Prepare to send status updates back to the main activity. * Get a local broadcast manager instance; broadcast intents sent via this * manager are only available within the this app. */ mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); /* * Create a new background thread with an associated Looper that processes Message objects * from a MessageQueue. The Looper allows test Activities to send repeated requests to * inject mock locations from this Service. */ mWorkThread = new HandlerThread("UpdateThread", Process.THREAD_PRIORITY_BACKGROUND); /* * Start the thread. Nothing actually runs until the Looper for this thread dispatches a * Message to the Handler. */ mWorkThread.start(); // Get the Looper for the thread mUpdateLooper = mWorkThread.getLooper(); /* * Create a Handler object and pass in the Looper for the thread. * The Looper can now dispatch Message objects to the Handler's handleMessage() method. */ mUpdateHandler = new UpdateHandler(mUpdateLooper); // Indicate that testing has not yet started mTestStarted = false; }
From source file:com.naman14.timber.musicplayer.MusicService.java
@Override public void onCreate() { if (D)/* w w w .j ava 2 s . co m*/ Log.d(TAG, "Creating service"); super.onCreate(); mNotificationManager = NotificationManagerCompat.from(this); // gets a pointer to the playback state store mPlaybackStateStore = MusicPlaybackState.getInstance(this); mSongPlayCount = SongPlayCount.getInstance(this); mRecentStore = RecentStore.getInstance(this); mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND); mHandlerThread.start(); mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper()); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mMediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()); mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setUpMediaSession(); } mPreferences = getSharedPreferences("Service", 0); // mCardId = getCardId(); // registerExternalStorageListener(); mPlayer = new MultiPlayer2(this); mPlayer.setHandler(mPlayerHandler); // Initialize the intent filter and each action final IntentFilter filter = new IntentFilter(); filter.addAction(SERVICECMD); filter.addAction(TOGGLEPAUSE_ACTION); filter.addAction(PAUSE_ACTION); filter.addAction(STOP_ACTION); filter.addAction(NEXT_ACTION); filter.addAction(PREVIOUS_ACTION); filter.addAction(PREVIOUS_FORCE_ACTION); filter.addAction(REPEAT_ACTION); filter.addAction(SHUFFLE_ACTION); // Attach the broadcast listener registerReceiver(mIntentReceiver, filter); // mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler); // getContentResolver().registerContentObserver( // MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true, mMediaStoreObserver); // getContentResolver().registerContentObserver( // MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mMediaStoreObserver); // Initialize the wake lock final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); mWakeLock.setReferenceCounted(false); final Intent shutdownIntent = new Intent(this, MusicService.class); shutdownIntent.setAction(SHUTDOWN); mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0); scheduleDelayedShutdown(); // reloadQueueAfterPermissionCheck(); notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); }
From source file:io.github.msc42.masterthemaze.GameActivity.java
private void startGameThreads() { mGameThreadMessageHandler = new Handler(Looper.getMainLooper()) { @Override/* w w w . jav a 2s. c om*/ public void handleMessage(Message message) { super.handleMessage(message); switch (message.what) { case Constants.INVALID_LEVEL_MESSAGE: String errorMessage = (String) message.obj; showInvalidLevelDialog(errorMessage); break; case Constants.IO_ERROR_MESSAGE: showIoErrorDialog(); break; case Constants.BT_ESTABLISHED_CONNECTION_MESSAGE: showBluetoothEstablishedConnectionScreen(); break; case Constants.BT_CANNOT_ESTABLISH_CONNECTION_MESSAGE: showBluetoothCannotEstablishConnectionDialog(); break; case Constants.FAILED_HANDSHAKE_MESSAGE: showFailedHandshakeDialog(); break; case Constants.BT_BEGIN_IO_ERROR_MESSAGE: showBtBeginIoErrorDialog(); break; case Constants.BT_END_IO_ERROR_MESSAGE: if (mBluetoothIoErrorDialog != null) { mBluetoothIoErrorDialog.cancel(); } break; case Constants.BT_IO_ERROR_MESSAGE: showBtSendIoErrorDialog(); break; case Constants.DISABLED_BLUETOOTH_MESSAGE: showDoNotDisableBluetoothDialog(); break; case Constants.RFCOMM_SOCKET_NOT_SUPPORTED_MESSAGE: showRfcommSocketNotSupportedDialog(); break; default: // all possible messages should get a case break; } } }; mGameThread = new GameThread(mGame, mMotionQueue, mBluetoothDevice, mGameThreadMessageHandler); mGameThread.start(); if (mMotion) { mSensorHandlerThread = new HandlerThread("SensorHandlerThread", Process.THREAD_PRIORITY_URGENT_DISPLAY); mSensorHandlerThread.start(); mSensorHandler = new Handler(mSensorHandlerThread.getLooper()); mAccelerometerEventListener = new AccelerometerEventListener(mRotation, mSensitivity, mCurrentMoveDirection, mMotionQueue); } }
From source file:cc.mintcoin.wallet.ui.SendCoinsFragment.java
@Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true);//from w w w. j a va2 s . c o m bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND); backgroundThread.start(); backgroundHandler = new Handler(backgroundThread.getLooper()); }