List of usage examples for android.os HandlerThread HandlerThread
public HandlerThread(String name)
From source file:com.fastbootmobile.encore.service.PlaybackService.java
/** * Called when the service is created//from w w w . j a v a 2 s .c o m */ @Override public void onCreate() { super.onCreate(); mListenLogger = new ListenLogger(this); mPrefetcher = new Prefetcher(this); mCommandsHandlerThread = new HandlerThread("PlaybackServiceCommandsHandler"); mCommandsHandlerThread.start(); mCommandsHandler = new CommandHandler(this, mCommandsHandlerThread); // Register package manager to receive updates mPacManReceiver = new PacManReceiver(); IntentFilter pacManFilter = new IntentFilter(); pacManFilter.addAction(Intent.ACTION_PACKAGE_ADDED); pacManFilter.addAction(Intent.ACTION_PACKAGE_CHANGED); pacManFilter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED); pacManFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); pacManFilter.addAction(Intent.ACTION_PACKAGE_REPLACED); pacManFilter.addDataScheme("package"); registerReceiver(mPacManReceiver, pacManFilter); // Really Google, I'd love to use your new APIs... But they're not working. If you use // the new Lollipop metadata system, you lose Bluetooth AVRCP since the Bluetooth // package still use the old RemoteController system. /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mRemoteMetadata = new RemoteMetadataManagerv21(this); } else*/ { mRemoteMetadata = new RemoteMetadataManager(this); } ProviderAggregator.getDefault().addUpdateCallback(this); // Native playback initialization mNativeHub = new NativeHub(getApplicationContext()); mNativeSink = new NativeAudioSink(); mNativeHub.setSinkPointer(mNativeSink.getPlayer().getHandle()); mNativeHub.setOnAudioWrittenListener(this); mNativeHub.onStart(); mDSPProcessor = new DSPProcessor(this); mDSPProcessor.restoreChain(this); // Plugins initialization PluginsLookup.getDefault().initialize(getApplicationContext()); PluginsLookup.getDefault().registerProviderListener(this); List<ProviderConnection> connections = PluginsLookup.getDefault().getAvailableProviders(); for (ProviderConnection conn : connections) { if (conn.getBinder(false) != null) { assignProviderAudioSocket(conn); } else { Log.w(TAG, "Cannot assign audio socket to " + conn.getIdentifier() + ", binder is null"); } } // Setup mIsStopping = false; // Bind to all provider List<ProviderConnection> providers = PluginsLookup.getDefault().getAvailableProviders(); for (ProviderConnection pc : providers) { try { IMusicProvider binder = pc.getBinder(false); if (binder != null) { binder.registerCallback(mProviderCallback); } } catch (RemoteException e) { Log.e(TAG, "Cannot register callback", e); } } // Register AutoMix manager mCallbacks.add(AutoMixManager.getDefault()); // Setup notification system mNotification = new ServiceNotification(this); mNotification.setOnNotificationChangedListener(new ServiceNotification.NotificationChangedListener() { @Override public void onNotificationChanged(ServiceNotification notification) { NotificationManagerCompat nmc = NotificationManagerCompat.from(PlaybackService.this); if (mIsForeground) { notification.notify(nmc); mIsForeground = true; } else { notification.notify(PlaybackService.this); } BitmapDrawable albumArt = notification.getAlbumArt(); mRemoteMetadata.setAlbumArt(albumArt); } }); // Setup lockscreen remote controls mRemoteMetadata.setup(); // Setup playback wakelock (but don't acquire it yet) PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "OmniMusicPlayback"); // Restore preferences SharedPreferences prefs = getSharedPreferences(SERVICE_SHARED_PREFS, MODE_PRIVATE); mRepeatMode = prefs.getBoolean(PREF_KEY_REPEAT, false); mShuffleMode = prefs.getBoolean(PREF_KEY_SHUFFLE, false); // TODO: Use callbacks // Restore playback queue after one second - we have multiple things to wait here: // - The callbacks of the main app's UI // - The providers connecting // - The providers ready to send us data mHandler.postDelayed(new Runnable() { @Override public void run() { SharedPreferences queuePrefs = getSharedPreferences(QUEUE_SHARED_PREFS, MODE_PRIVATE); mPlaybackQueue.restore(queuePrefs); mCurrentTrack = queuePrefs.getInt("current", -1); mCurrentTrackLoaded = false; mNotification.setHasNext(mPlaybackQueue.size() > 1 || (mPlaybackQueue.size() > 0 && mRepeatMode)); } }, 1000); }
From source file:org.alljoyn.bus.samples.simpleclient.DevicesActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_devices); mContext = this; // mEditText = (EditText) findViewById(R.id.EditText); // mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { // public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { // if (actionId == EditorInfo.IME_NULL // && event.getAction() == KeyEvent.ACTION_UP) { // /* Call the remote object's Ping method. */ // Message msg = mBusHandler.obtainMessage(BusHandler.PING, // view.getText().toString()); // mBusHandler.sendMessage(msg); // } // return true; // } // }); //Master data list Fragment String fullName = SERVICE_NAME + ".coffeemaker.Beagle_Bone"; String[] tokens = fullName.split("[.]"); for (String token : tokens) { Log.i("token:", token); }//from ww w . j a va2 s . c o m mDeviceListFragment = new DeviceListFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.myFragmentContainer, mDeviceListFragment, "DeviceListFragment"); fragmentTransaction.commit(); /* Make all AllJoyn calls through a separate handler thread to prevent blocking the UI. */ HandlerThread busThread = new HandlerThread("BusHandler"); busThread.start(); mBusHandler = new BusHandler(busThread.getLooper()); /* Connect to an AllJoyn object. */ mBusHandler.sendEmptyMessage(BusHandler.CONNECT); mHandler.sendEmptyMessage(MESSAGE_START_PROGRESS_DIALOG); }
From source file:com.android.providers.downloads.DownloadService.java
/** * Initializes the service when it is first created */// w w w . j a v a 2 s . c om @Override public void onCreate() { super.onCreate(); XLConfig.LOGD("(onCreate) ---> Service onCreate"); if (mSystemFacade == null) { mSystemFacade = new RealSystemFacade(this); } mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mStorageManager = new StorageManager(this); mUpdateThread = new HandlerThread(Constants.TAG + "-UpdateThread"); mUpdateThread.start(); mUpdateHandler = new Handler(mUpdateThread.getLooper(), mUpdateCallback); mScanner = new DownloadScanner(this); mNotifier = new DownloadNotifier(this); mNotifier.cancelAll(); mObserver = new DownloadManagerContentObserver(); getContentResolver().registerContentObserver(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, true, mObserver); // get mXunleiEngineEnable from DB mXunleiEngineEnable = Helpers.getXunleiUsagePermission(getApplicationContext()); if (mXunleiEngineEnable) { startGetXlTokenEx(false); initXunleiEngine(); } if (!miui.os.Build.IS_TABLET) { mCdnThread = new CdnQueryingThread(); mCdnThread.start(); } if (XLUtil.getNetwrokType(getApplicationContext()) == ConnectivityManager.TYPE_MOBILE) { mCloudControlThread = new MobileCloudCheckThread(); mCloudControlThread.start(); } String pkgName = getApplicationContext().getPackageName(); Helpers.trackDownloadServiceStatus(this.getApplicationContext(), DOWNLOAD_SERVICE_START, pkgName); // do track // Context ctx = getApplicationContext(); // String pkgName = ctx.getPackageName(); // Helpers.trackOnlineStatus(ctx, 0, 0, mXunleiEngineEnable, "", "", pkgName, PRODUCT_NAME, PRODUCT_VERSION); }
From source file:com.SecUpwN.AIMSICD.service.AimsicdService.java
public void onCreate() { //TelephonyManager provides system details tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mContext = getApplicationContext();//from ww w. j a v a 2 s. com PHONE_TYPE = tm.getPhoneType(); prefs = this.getSharedPreferences(AimsicdService.SHARED_PREFERENCES_BASENAME, 0); prefs.registerOnSharedPreferenceChangeListener(this); loadPreferences(); if (!CELL_TABLE_CLEANSED) { dbHelper.open(); dbHelper.cleanseCellTable(); dbHelper.close(); Editor prefsEditor; prefsEditor = prefs.edit(); prefsEditor.putBoolean(this.getString(R.string.pref_cell_table_cleansed), true); prefsEditor.apply(); } mDevice.refreshDeviceInfo(tm, this); //Telephony Manager setNotification(); mRequestExecutor = new SamsungMulticlientRilExecutor(); mRilExecutorDetectResult = mRequestExecutor.detect(); if (!mRilExecutorDetectResult.available) { mMultiRilCompatible = false; Log.e(TAG, "Samsung multiclient ril not available: " + mRilExecutorDetectResult.error); mRequestExecutor = null; } else { mRequestExecutor.start(); mMultiRilCompatible = true; //Sumsung MultiRil Initialization mHandlerThread = new HandlerThread("ServiceModeSeqHandler"); mHandlerThread.start(); Looper l = mHandlerThread.getLooper(); if (l != null) { mHandler = new Handler(l, new MyHandler()); } } //Register receiver for Silent SMS Interception Notification mContext.registerReceiver(mMessageReceiver, new IntentFilter(SILENT_SMS)); mMonitorCell = new Cell(); Log.i(TAG, "Service launched successfully"); }
From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java
@Override public void onCreate() { Log.v(TAG, "onCreate: "); super.onCreate(); mHandlerThread = new HandlerThread(TAG + "Thread"); mHandlerThread.start();/*from w w w . j av a 2 s . c om*/ mHandler = new _Handler(mHandlerThread.getLooper()); }
From source file:ac.robinson.bettertogether.hotspot.HotspotManagerService.java
@SuppressFBWarnings("REC_CATCH_EXCEPTION") @Nullable// w w w . j av a 2 s.c om @Override public IBinder onBind(Intent intent) { if (!mIsBound) { //TODO: check mBluetoothAdapter not null and/or check bluetooth is available - BluetoothUtils.isBluetoothAvailable() mBluetoothAdapter = BluetoothUtils.getBluetoothAdapter(HotspotManagerService.this); mOriginalBluetoothStatus = mBluetoothAdapter.isEnabled(); mOriginalBluetoothName = mBluetoothAdapter.getName(); //TODO: check mWifiManager not null and/or check bluetooth is available - WifiUtils.isWifiAvailable() // note we need the WifiManager for connecting to other hotspots regardless of whether we can create our own mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); // try to get the original state to restore later int wifiState = mWifiManager.getWifiState(); switch (wifiState) { case WifiManager.WIFI_STATE_ENABLED: case WifiManager.WIFI_STATE_ENABLING: mOriginalWifiStatus = true; break; case WifiManager.WIFI_STATE_DISABLED: case WifiManager.WIFI_STATE_DISABLING: case WifiManager.WIFI_STATE_UNKNOWN: mOriginalWifiStatus = false; break; default: break; } // try to save the existing hotspot state if (CREATE_WIFI_HOTSPOT_SUPPORTED) { try { // TODO: is it possible to save/restore the original password? (WifiConfiguration doesn't hold the password) WifiConfiguration wifiConfiguration = WifiUtils.getWifiHotspotConfiguration(mWifiManager); mOriginalHotspotConfiguration = new ConnectionOptions(); mOriginalHotspotConfiguration.mName = wifiConfiguration.SSID; } catch (Exception ignored) { // note - need to catch Exception rather than ReflectiveOperationException due to our API level (requires 19) } } // set up background thread for message sending - see: https://medium.com/@ali.muzaffar/dc8bf1540341 mMessageThread = new HandlerThread("BTMessageThread"); mMessageThread.start(); mMessageThreadHandler = new Handler(mMessageThread.getLooper()); // set up listeners for network/bluetooth state changes IntentFilter intentFilter = new IntentFilter(); if (CREATE_WIFI_HOTSPOT_SUPPORTED) { intentFilter.addAction(HOTSPOT_STATE_FILTER); // Wifi hotspot states } intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); // Wifi on/off intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); // network connection/disconnection intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // Bluetooth on/off intentFilter.addAction(BluetoothDevice.ACTION_FOUND); // Bluetooth device found registerReceiver(mGlobalBroadcastReceiver, intentFilter); // listen for messages from our PluginMessageReceiver IntentFilter localIntentFilter = new IntentFilter(); localIntentFilter.addAction(PluginIntent.ACTION_MESSAGE_RECEIVED); localIntentFilter.addAction(PluginIntent.ACTION_STOP_PLUGIN); LocalBroadcastManager.getInstance(HotspotManagerService.this).registerReceiver(mLocalBroadcastReceiver, localIntentFilter); // listen for EventBus events (from wifi/bluetooth servers) if (!EventBus.getDefault().isRegistered(HotspotManagerService.this)) { EventBus.getDefault().register(HotspotManagerService.this); } mIsBound = true; } return mMessenger.getBinder(); }
From source file:com.obviousengine.android.focus.ZslFocusCamera.java
/** * Instantiates a new camera based on Camera 2 API. * * @param device The underlying Camera 2 device. * @param characteristics The device's characteristics. * @param pictureSize the size of the final image to be taken. */// w w w . jav a2s . co m ZslFocusCamera(CameraDevice device, CameraCharacteristics characteristics, Size pictureSize) { Timber.v("Creating new ZslFocusCamera"); this.device = device; this.characteristics = characteristics; fullSizeAspectRatio = calculateFullSizeAspectRatio(characteristics); cameraThread = new HandlerThread("FocusCamera"); // If this thread stalls, it will delay viewfinder frames. cameraThread.setPriority(Thread.MAX_PRIORITY); cameraThread.start(); cameraHandler = new Handler(cameraThread.getLooper()); cameraListenerThread = new HandlerThread("FocusCamera-Listener"); cameraListenerThread.start(); cameraListenerHandler = new Handler(cameraListenerThread.getLooper()); // TODO: Encoding on multiple cores results in preview jank due to // excessive GC. int numEncodingCores = Utils.getNumCpuCores(); imageSaverThreadPool = new ThreadPoolExecutor(numEncodingCores, numEncodingCores, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); captureManager = new ImageCaptureManager(MAX_CAPTURE_IMAGES, cameraListenerHandler, imageSaverThreadPool); captureManager.setCaptureReadyListener(new ImageCaptureManager.CaptureReadyListener() { @Override public void onReadyStateChange(boolean capturePossible) { readyStateManager.setInput(ReadyStateRequirement.CAPTURE_MANAGER_READY, capturePossible); } }); // Listen for changes to auto focus state and dispatch to // focusStateListener. captureManager.addMetadataChangeListener(CaptureResult.CONTROL_AF_STATE, new ImageCaptureManager.MetadataChangeListener() { @Override public void onImageMetadataChange(Key<?> key, Object oldValue, Object newValue, CaptureResult result) { if (focusStateListener == null) { return; } focusStateListener.onFocusStatusUpdate( AutoFocusHelper.stateFromCamera2State(result.get(CaptureResult.CONTROL_AF_STATE)), result.getFrameNumber()); } }); // Allocate the image reader to store all images received from the // camera. if (pictureSize == null) { // TODO The default should be selected by the caller, and // pictureSize should never be null. pictureSize = getDefaultPictureSize(); } captureImageReader = ImageReader.newInstance(pictureSize.getWidth(), pictureSize.getHeight(), CAPTURE_IMAGE_FORMAT, MAX_CAPTURE_IMAGES); captureImageReader.setOnImageAvailableListener(captureManager, cameraHandler); mediaActionSound.load(MediaActionSound.SHUTTER_CLICK); }
From source file:com.microsoft.projectoxford.emotionsample.RecognizeActivity.java
protected void startBackgroundThread() { mBackgroundThread = new HandlerThread("Camera Background"); mBackgroundThread.start();// w ww. j a v a 2 s .c o m mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); }
From source file:eu.faircode.netguard.SinkholeService.java
@Override public void onCreate() { super.onCreate(); Log.i(TAG, "Create"); HandlerThread thread = new HandlerThread(getString(R.string.app_name)); thread.start();/*from ww w .jav a2 s .c om*/ mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); // Listen for interactive state changes IntentFilter ifInteractive = new IntentFilter(); ifInteractive.addAction(Intent.ACTION_SCREEN_ON); ifInteractive.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(interactiveStateReceiver, ifInteractive); // Listen for connectivity updates IntentFilter ifConnectivity = new IntentFilter(); ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(connectivityChangedReceiver, ifConnectivity); // Listen for added applications IntentFilter ifPackage = new IntentFilter(); ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED); ifPackage.addDataScheme("package"); registerReceiver(packageAddedReceiver, ifPackage); }
From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java
/** Called when the activity is first created. */ @Override/*from ww w. j ava 2 s . c o m*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Restore preferences this.uiHandler = new Handler(); HandlerThread bgThread = new HandlerThread("background"); bgThread.start(); this.backgroundHandler = new Handler(bgThread.getLooper()); }