Example usage for android.os HandlerThread start

List of usage examples for android.os HandlerThread start

Introduction

In this page you can find the example usage for android.os HandlerThread start.

Prototype

public synchronized void start() 

Source Link

Document

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Usage

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

@Override
public void onCreate() {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Native init
    jni_init();/*from w  w  w.  j a v a2  s.c o m*/
    boolean pcap = prefs.getBoolean("pcap", false);
    setPcap(pcap, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    Util.setTheme(this);
    super.onCreate();

    HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command",
            Process.THREAD_PRIORITY_FOREGROUND);
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log",
            Process.THREAD_PRIORITY_BACKGROUND);
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats",
            Process.THREAD_PRIORITY_BACKGROUND);
    commandThread.start();
    logThread.start();
    statsThread.start();

    commandLooper = commandThread.getLooper();
    logLooper = logThread.getLooper();
    statsLooper = statsThread.getLooper();

    commandHandler = new CommandHandler(commandLooper);
    logHandler = new LogHandler(logLooper);
    statsHandler = new StatsHandler(statsLooper);

    // Listen for power save mode
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !Util.isPlayStoreInstall(this)) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        powersaving = pm.isPowerSaveMode();
        IntentFilter ifPower = new IntentFilter();
        ifPower.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        registerReceiver(powerSaveReceiver, ifPower);
        registeredPowerSave = true;
    }

    // Listen for user switches
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        IntentFilter ifUser = new IntentFilter();
        ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
        ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
        registerReceiver(userReceiver, ifUser);
        registeredUser = true;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Listen for idle mode state changes
        IntentFilter ifIdle = new IntentFilter();
        ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        registerReceiver(idleStateReceiver, ifIdle);
        registeredIdleState = true;
    }

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);
    registeredConnectivityChanged = true;

    // Listen for added applications
    IntentFilter ifPackage = new IntentFilter();
    ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    ifPackage.addDataScheme("package");
    registerReceiver(packageAddedReceiver, ifPackage);
    registeredPackageAdded = true;

    // Setup house holding
    Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
    alarmIntent.setAction(ACTION_HOUSE_HOLDING);
    PendingIntent pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000,
            AlarmManager.INTERVAL_HALF_DAY, pi);
}

From source file:com.android.server.MountService.java

/**
 * Constructs a new MountService instance
 *
 * @param context  Binder context for this service
 *//*from   w  ww.  j ava  2 s .  co  m*/
public MountService(Context context) {
    sSelf = this;

    mContext = context;

    synchronized (mVolumesLock) {
        readStorageListLocked();
    }

    // XXX: This will go away soon in favor of IMountServiceObserver
    mPms = (PackageManagerService) ServiceManager.getService("package");

    HandlerThread hthread = new HandlerThread(TAG);
    hthread.start();
    mHandler = new MountServiceHandler(hthread.getLooper());

    // Watch for user changes
    final IntentFilter userFilter = new IntentFilter();
    userFilter.addAction(Intent.ACTION_USER_ADDED);
    userFilter.addAction(Intent.ACTION_USER_REMOVED);
    mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);

    // Watch for USB changes on primary volume
    final StorageVolume primary = getPrimaryPhysicalVolume();
    if (primary != null && primary.allowMassStorage()) {
        mContext.registerReceiver(mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
    }

    // Add OBB Action Handler to MountService thread.
    mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());

    // Initialize the last-fstrim tracking if necessary
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
    if (!mLastMaintenanceFile.exists()) {
        // Not setting mLastMaintenance here means that we will force an
        // fstrim during reboot following the OTA that installs this code.
        try {
            (new FileOutputStream(mLastMaintenanceFile)).close();
        } catch (IOException e) {
            Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
        }
    } else {
        mLastMaintenance = mLastMaintenanceFile.lastModified();
    }

    /*
     * Create the connection to vold with a maximum queue of twice the
     * amount of containers we'd ever expect to have. This keeps an
     * "asec list" from blocking a thread repeatedly.
     */
    mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25, null);

    Thread thread = new Thread(mConnector, VOLD_TAG);
    thread.start();

    // Add ourself to the Watchdog monitors if enabled.
    if (WATCHDOG_ENABLE) {
        Watchdog.getInstance().addMonitor(this);
    }
}

From source file:org.kontalk.service.msgcenter.MessageCenterService.java

private void createIdleHandler() {
    HandlerThread thread = new HandlerThread("IdleThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    int refCount = Kontalk.get(this).getReferenceCounter();
    mIdleHandler = new IdleConnectionHandler(this, refCount, thread.getLooper());
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

@Override
public void onCreate() {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Native init
    jni_init();/*from ww w .  ja  v a 2  s .  co m*/
    boolean pcap = prefs.getBoolean("pcap", false);
    setPcap(pcap, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    Util.setTheme(this);
    super.onCreate();

    HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command",
            Process.THREAD_PRIORITY_FOREGROUND);
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log",
            Process.THREAD_PRIORITY_BACKGROUND);
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats",
            Process.THREAD_PRIORITY_BACKGROUND);
    commandThread.start();
    logThread.start();
    statsThread.start();

    commandLooper = commandThread.getLooper();
    logLooper = logThread.getLooper();
    statsLooper = statsThread.getLooper();

    commandHandler = new CommandHandler(commandLooper);
    logHandler = new LogHandler(logLooper);
    statsHandler = new StatsHandler(statsLooper);

    // Listen for power save mode
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !Util.isPlayStoreInstall(this)) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        powersaving = pm.isPowerSaveMode();
        IntentFilter ifPower = new IntentFilter();
        ifPower.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        registerReceiver(powerSaveReceiver, ifPower);
        registeredPowerSave = true;
    }

    // Listen for user switches
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        IntentFilter ifUser = new IntentFilter();
        ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
        ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
        registerReceiver(userReceiver, ifUser);
        registeredUser = true;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Listen for idle mode state changes
        IntentFilter ifIdle = new IntentFilter();
        ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        registerReceiver(idleStateReceiver, ifIdle);
        registeredIdleState = true;
    }

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);
    registeredConnectivityChanged = true;

    // Listen for added applications
    IntentFilter ifPackage = new IntentFilter();
    ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    ifPackage.addAction(Intent.ACTION_PACKAGE_REMOVED);
    ifPackage.addDataScheme("package");
    registerReceiver(packageChangedReceiver, ifPackage);
    registeredPackageChanged = true;

    // Setup house holding
    Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
    alarmIntent.setAction(ACTION_HOUSE_HOLDING);
    PendingIntent pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000,
            AlarmManager.INTERVAL_HALF_DAY, pi);
}

From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java

/** Called when the activity is first created. */
@Override//  w ww .  jav a  2s. 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());
}

From source file:io.realm.RealmTests.java

@Test
public void closeRealmInChangeListener() {
    realm.close();/*from   w  ww  .ja va 2s  .c  om*/
    final CountDownLatch signalTestFinished = new CountDownLatch(1);
    HandlerThread handlerThread = new HandlerThread("background");
    handlerThread.start();
    final Handler handler = new Handler(handlerThread.getLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            final Realm realm = Realm.getInstance(realmConfig);
            final RealmChangeListener listener = new RealmChangeListener() {
                @Override
                public void onChange() {
                    if (realm.where(AllTypes.class).count() == 1) {
                        realm.removeChangeListener(this);
                        realm.close();
                        signalTestFinished.countDown();
                    }
                }
            };

            realm.addChangeListener(listener);

            realm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.createObject(AllTypes.class);
                }
            });
        }
    });
    TestHelper.awaitOrFail(signalTestFinished);
}

From source file:net.zorgblub.typhon.fragment.ReadingFragment.java

/**
 * Called when the activity is first created.
 *//*  w ww.j av  a  2s.c  om*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Typhon.getComponent().inject(this);

    // Restore preferences
    this.uiHandler = new Handler();
    HandlerThread bgThread = new HandlerThread("background");
    bgThread.start();
    this.backgroundHandler = new Handler(bgThread.getLooper());
    dictionaryService = DictionaryServiceImpl.get();
    dictionaryLastUpdate = dictionaryService.getLastUpdateTimestamp();
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

/** Called when the activity is first created. */
@Override//from   w  ww  .  ja  v a2  s .co 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());

}

From source file:com.kaichaohulian.baocms.ecdemo.ui.chatting.ChattingFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    LogUtil.d(TAG, "onActivityCreated");
    super.onActivityCreated(savedInstanceState);
    // ???//w ww.ja  v  a 2s  .c om
    initView();

    queryUIMessage();

    // ?IM?API
    mChatManager = SDKCoreHelper.getECChatManager();
    HandlerThread thread = new HandlerThread("ChattingVoiceRecord",
            android.os.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();
        }
    });

    registerReceiver(
            new String[] { IMessageSqlManager.ACTION_GROUP_DEL, IMChattingHelper.INTENT_ACTION_CHAT_USER_STATE,
                    IMChattingHelper.INTENT_ACTION_CHAT_EDITTEXT_FOUCU });
}

From source file:com.andrew.apollo.MusicPlaybackService.java

private void initService() {
    // Initialize the favorites and recents databases
    mFavoritesCache = FavoritesStore.getInstance(this);
    mRecentsCache = RecentStore.getInstance(this);

    // Initialize the notification helper
    mNotificationHelper = new NotificationHelper(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.
    final HandlerThread thread = new HandlerThread("MusicPlayerHandler",
            android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Initialize the handler
    mPlayerHandler = new MusicPlayerHandler(this, thread.getLooper());

    // Initialize the audio manager and register any headset controls for
    // playback//w w  w.  j a va  2 s  .  co  m
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    try {
        if (mAudioManager != null) {
            mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);
        }
    } catch (SecurityException e) {
        e.printStackTrace();
        // ignore
        // some times the phone does not grant the MODIFY_PHONE_STATE permission
        // this permission is for OMEs and we can't do anything about it
    }

    // Use the remote control APIs to set the playback state
    setUpRemoteControlClient();

    // Initialize the preferences
    mPreferences = getSharedPreferences("Service", 0);
    mCardId = getCardId();

    registerExternalStorageListener();

    // Initialize the media player
    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mPlayerHandler);

    ConfigurationManager CM = ConfigurationManager.instance();
    // Load Repeat Mode
    setRepeatMode(CM.getInt(Constants.PREF_KEY_GUI_PLAYER_REPEAT_MODE));
    // Load Shuffle Mode On/Off
    enableShuffle(CM.getBoolean(Constants.PREF_KEY_GUI_PLAYER_SHUFFLE_ENABLED));
    MusicUtils.isShuffleEnabled();

    // 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(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    // Initialize the wake lock
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (powerManager != null) {
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
        mWakeLock.setReferenceCounted(false);
    }
    // Initialize the delayed shutdown intent
    final Intent shutdownIntent = new Intent(this, MusicPlaybackService.class);
    shutdownIntent.setAction(SHUTDOWN_ACTION);

    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(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
    updateNotification();
}