List of usage examples for android.os HandlerThread start
public synchronized void start()
From source file:com.bitants.wally.activities.ImageDetailsActivity.java
private void setupHandlers() { HandlerThread handlerThread = new HandlerThread("background"); handlerThread.start(); backgroundHandler = new Handler(handlerThread.getLooper(), this); uiHandler = new Handler(getMainLooper(), this); }
From source file:de.dcja.prettygreatmusicplayer.MusicPlaybackService.java
@Override public synchronized void onCreate() { Log.i(TAG, "Music Playback Service Created!"); isRunning = true;//from w w w . j ava 2 s . co 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.smithdtyler.prettygoodmusicplayer.MusicPlaybackService.java
@Override public synchronized void onCreate() { Log.i(TAG, "Music Playback Service Created!"); isRunning = true;//from w ww . jav a2 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(); } }); // 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.android.calendar.alerts.AlertService.java
@Override public void onCreate() { HandlerThread thread = new HandlerThread("AlertService", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); // Flushes old fired alerts from internal storage, if needed. AlertUtils.flushOldAlertsFromInternalStorage(getApplication()); }
From source file:eu.fistar.sdcs.pa.PAManagerService.java
/** * Discover all the DA available on the system *///w w w .ja v a 2s .co m private void discoverDAs() { Log.i(PAAndroidConstants.PA_LOGTAG, "Starting Device Adapter discovery"); // Create the Intent to broadcast Intent intent = new Intent(DA_DISCOVERY.REQUEST_ACTION); intent.putExtra(DA_DISCOVERY.BUNDLE_REPACT, DA_DISCOVERY.REPLY_ACTION); // Create the Intent Filter to receive broadcast replies IntentFilter filter = new IntentFilter(); filter.addAction(DA_DISCOVERY.REPLY_ACTION); // Register the Broadcast Receiver for replies and set it to run in another thread HandlerThread ht = new HandlerThread("ht"); ht.start(); registerReceiver(broadcastDiscoveryDA, filter, null, new Handler(ht.getLooper())); // Send in broadcast the Intent for discovery sendBroadcast(intent); // Create a new Thread object to stop the discovery and also use it as a lock ScanningStopAndLock r = new ScanningStopAndLock(); // Set the timeout for receiving replies r.start(); // Wait for the scanning to be done before returning synchronized (r) { while (!r.isDiscoveryDone()) { try { r.wait(); } catch (InterruptedException e) { // Just wait until scanning is done } } } }
From source file:com.cssweb.android.trade.stock.StockTrading.java
@Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); sc = new ServiceControl(this);//?? ///*from w w w.j a v a 2 s .c o m*/ HandlerThread mHandlerThread = new HandlerThread("CSSWEB_THREAD"); mHandlerThread.start(); priceHandler = new PriceDataHandler(mHandlerThread.getLooper()); setContentView(com.cssweb.android.main.R.layout.zr_trade_stock_trade); Bundle bundle = getIntent().getExtras(); type = bundle.getInt("type"); bsname = bundle.getString("bsname"); String stockCode = bundle.getString("stkcode"); initTitle(R.drawable.njzq_title_left_back, 0, bsname); LinearLayout localLinearLayout = (LinearLayout) findViewById(R.id.zrtradelayout); localLinearLayout.setOnFocusChangeListener(setOnEditFocusListener); this.m_vklayout = localLinearLayout; View localView1 = this.m_vklayout; localView1.setOnFocusChangeListener(setOnEditFocusListener); View localView2 = this.m_vklayout; localView2.setOnClickListener(setOnEditClickListener); viewFlipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper01); preView = (ImageView) findViewById(R.id.previous_screen); leftIn = AnimationUtils.loadAnimation(this, R.anim.push_left_in_layout); leftOut = AnimationUtils.loadAnimation(this, R.anim.push_left_out_layout); rightIn = AnimationUtils.loadAnimation(this, R.anim.push_right_in_layout); rightOut = AnimationUtils.loadAnimation(this, R.anim.push_right_out_layout); priceView = (PriceMini) findViewById(R.id.zrviewprice); trendView = (TrendView) findViewById(R.id.zrviewtrend); trendView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }); klineView = (KlineMini) findViewById(R.id.zrviewkline); klineView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }); financeView = (FinanceMini) findViewById(R.id.zrviewfinance); stockHolder = (Spinner) findViewById(R.id.zrtxtaccount); queryMethod = (Spinner) findViewById(R.id.zrtxtbsflag); // availableNum = (SeekBar) findViewById(R.id.zrcanbs); // lblMaxNumber = (TextView)findViewById(R.id.txtMaxNumber); stkcode = (EditText) findViewById(R.id.zredtstockcode); stkname = (TextView) findViewById(R.id.zrtxtstockname); price = (EditText) findViewById(R.id.zredtprice); number = (EditText) findViewById(R.id.zredtcount); lblNumberUnit = (TextView) findViewById(R.id.lblNumberUnit); btn0 = (ShadowButton) findViewById(R.id.zr_surebutton); btn0.setOnClickListener(myShowProgreeBar); layoutprice0 = (LinearLayout) findViewById(R.id.LinearLayout03); layoutprice = (LinearLayout) findViewById(R.id.LinearLayout11); //layoutAvaiNumber = (LinearLayout)findViewById(R.id.LinearLayout04); //layoutAvaiAsset = (LinearLayout)findViewById(R.id.LinearLayout06); lblAvaiAsset = (TextView) findViewById(R.id.lblAvaiAsset); AvaiAsset = (TextView) findViewById(R.id.AvaiAsset); lblPrice = (TextView) findViewById(R.id.lblPrice); lblPrice1 = (TextView) findViewById(R.id.lblPrice1); lblNumber = (TextView) findViewById(R.id.lblNumber); avaiAsset = (TextView) findViewById(R.id.AvaiAsset); lblNumberUnit = (TextView) findViewById(R.id.lblNumberUnit); setDynamic(); adjustDownPrice = (ImageView) findViewById(R.id.AdjustDownPrice); adjustDownPrice.setTag(0); adjustDownPrice.setOnClickListener(adjustIconListener); adjustUpPrice = (ImageView) findViewById(R.id.AdjustUpPrice); adjustUpPrice.setTag(1); adjustUpPrice.setOnClickListener(adjustIconListener); adjustDownNumber = (ImageView) findViewById(R.id.AdjustDownNumber); adjustDownNumber.setTag(2); adjustDownNumber.setOnClickListener(adjustIconListener); adjustUpNumber = (ImageView) findViewById(R.id.AdjustUpNumber); adjustUpNumber.setTag(3); adjustUpNumber.setOnClickListener(adjustIconListener); stkcode.setText(stockCode); if (stkcode.getText().length() == 6) { showProgress(); } stkcode.setInputType(InputType.TYPE_NULL); stkcode.setFocusable(true); stkcode.setTag("STOCK"); stkcode.setOnClickListener(setOnEditClickListener); stkcode.setOnFocusChangeListener(setOnEditFocusListener); price.setInputType(InputType.TYPE_NULL); price.setFocusable(true); price.setTag("NUMDOT"); price.setOnClickListener(setOnEditClickListener); price.setOnFocusChangeListener(setOnEditFocusListener); number.setInputType(InputType.TYPE_NULL); number.setFocusable(true); number.setTag(""); number.setOnClickListener(setOnEditClickListener); number.setOnFocusChangeListener(setOnEditFocusListener); stkcode.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable arg0) { //queryStock(queryCode.getText()); OnTextChanged(arg0); } public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } }); holder = TradeUser.getInstance().getHolder(); stockHolderAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, (String[]) holder.toArray(new String[holder.size()])); stockHolderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); stockHolder.setAdapter(stockHolderAdapter); String[] arrayOfString = getResources().getStringArray(R.array.other_market_bs_methods); for (int i = 0; i < arrayOfString.length; i++) { Log.e("arrayOfString", arrayOfString[i]); } queryMethodAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayOfString); queryMethodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); queryMethod.setAdapter(queryMethodAdapter); queryMethod.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != 0) { layoutprice0.setVisibility(View.GONE); layoutprice.setVisibility(View.VISIBLE); } else { layoutprice0.setVisibility(View.VISIBLE); layoutprice.setVisibility(View.GONE); } } public void onNothingSelected(AdapterView<?> arg0) { } }); int h = R.drawable.forminput; Resources localResources = getResources(); Drawable localDrawable = null; localDrawable = localResources.getDrawable(h); int spinnerheight = localDrawable.getIntrinsicHeight() - 4; // Log.e("<<<<<<<<<<<<<<<<<<<eeeeeeeeeeeeeeeeeeeeeeeeeee>>>>>>>>>>>>>>", String.valueOf(spinnerheight)); LinearLayout.LayoutParams linearParams1 = (LinearLayout.LayoutParams) stockHolder.getLayoutParams();//?stockHolder? linearParams1.height = spinnerheight;//?? stockHolder.setLayoutParams(linearParams1); LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) queryMethod.getLayoutParams();//?queryMethod? linearParams.height = spinnerheight;//?? queryMethod.setLayoutParams(linearParams); }
From source file:org.runbuddy.tomahawk.services.PlaybackService.java
private void initMediaSession() { ComponentName componentName = new ComponentName(this, MediaButtonReceiver.class); mMediaSession = new MediaSessionCompat(getApplicationContext(), "Tomahawk", componentName, null); mMediaSession.setFlags(/*from w w w. j a va 2 s. c om*/ MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS); Intent intent = new Intent(PlaybackService.this, TomahawkMainActivity.class); intent.setAction(TomahawkMainActivity.SHOW_PLAYBACKFRAGMENT_ON_STARTUP); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(PlaybackService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); mMediaSession.setSessionActivity(pendingIntent); HandlerThread thread = new HandlerThread("playbackservice_callback"); thread.start(); mCallbackHandler = new Handler(thread.getLooper()); mMediaSession.setCallback(mMediaSessionCallback, mCallbackHandler); mMediaSession.setRatingType(RatingCompat.RATING_HEART); Bundle extras = new Bundle(); extras.putString(EXTRAS_KEY_PLAYBACKMANAGER, mPlaybackManager.getId()); mMediaSession.setExtras(extras); updateMediaPlayState(); setSessionToken(mMediaSession.getSessionToken()); }
From source file:com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.java
/** * Schedule an auto-reconnect attempt using backoff logic. * * @return true if attempt was scheduled, false otherwise. *///from w w w. ja v a 2 s .c o m private boolean scheduleReconnect() { LOGGER.info("schedule Reconnect attempt " + autoReconnectsAttempted + " of " + maxAutoReconnectAttempts + " in " + currentReconnectRetryTime + " seconds."); // schedule a reconnect if unlimited or if we haven't yet hit the limit if (maxAutoReconnectAttempts == -1 || autoReconnectsAttempted < maxAutoReconnectAttempts) { //Start a separate thread to do reconnect, because connection must not occur on the main thread. final HandlerThread ht = new HandlerThread("Reconnect thread"); ht.start(); Looper looper = ht.getLooper(); Handler handler = new Handler(looper); handler.postDelayed(new Runnable() { @Override public void run() { LOGGER.debug("TID: " + ht.getThreadId() + " trying to reconnect to session"); if (mqttClient != null && !mqttClient.isConnected()) { reconnectToSession(); } } }, MILLIS_IN_ONE_SECOND * currentReconnectRetryTime); currentReconnectRetryTime = Math.min(currentReconnectRetryTime * 2, maxReconnectRetryTime); return true; } else { LOGGER.warn("schedule reconnect returns false"); return false; } }
From source file:uk.co.pjmobile.mobile_apps.page_turner_reader.ReadingActivity.java
/** Called when the activity is first created. */ @Override// w w w. j av a 2 s . c o m 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.speedtong.example.ui.chatting.ChattingActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { LogUtil.d(TAG, "onCreate"); super.onCreate(savedInstanceState); brand = Build.MODEL + Build.BRAND;//from w w w . j av a 2 s . c o m TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); uuid = tm.getDeviceId(); messageDao = MessageDao.getInstance(this); toast = Toast.makeText(this, "", Toast.LENGTH_SHORT); sdpath = Environment.getExternalStorageDirectory().getAbsolutePath(); // ??? initView(); // ??? initActivityState(savedInstanceState); final ArrayList<ECMessage> list = IMessageSqlManager.queryIMessageList(mThread, 20, getMessageAdapterLastMessageTime() + ""); mListView.post(new Runnable() { @Override public void run() { mChattingAdapter.setData(list); if (mChattingAdapter.getCount() < 20) { //mPullDownView.setPullEnabled(false); //mPullDownView.setPullViewVisibed(false); } mListView.clearFocus(); mChattingAdapter.notifyDataSetChanged(); mListView.setSelection(mChattingAdapter.getCount()); } }); // ?IM?API mChatManager = SDKCoreHelper.getECChatManager(); HandlerThread thread = new HandlerThread("ChattingVoiceRecord", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); // Get the HandlerThread's Looper and use it for our Handler mChattingLooper = thread.getLooper(); mVoiceHandler = new Handler(mChattingLooper); mVoiceHandler.post(new Runnable() { @Override public void run() { doEmojiPanel(); } }); }