Example usage for android.content Intent ACTION_POWER_DISCONNECTED

List of usage examples for android.content Intent ACTION_POWER_DISCONNECTED

Introduction

In this page you can find the example usage for android.content Intent ACTION_POWER_DISCONNECTED.

Prototype

String ACTION_POWER_DISCONNECTED

To view the source code for android.content Intent ACTION_POWER_DISCONNECTED.

Click Source Link

Document

Broadcast Action: External power has been removed from the device.

Usage

From source file:org.alpine_toolkit.AlpineToolkitService.java

@Override
public void onCreate() {
    Log.i(LOG_TAG, "onCreate");
    super.onCreate();

    if (m_battery_receiver == null) { // Fixme: ???
        m_battery_receiver = new BatteryReceiver();
        IntentFilter intent_filter = new IntentFilter();
        intent_filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intent_filter.addAction(Intent.ACTION_POWER_CONNECTED);
        intent_filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        intent_filter.addAction(Intent.ACTION_BATTERY_LOW);
        intent_filter.addAction(Intent.ACTION_BATTERY_OKAY);
        registerReceiver(m_battery_receiver, intent_filter);
    }//www.  ja  va 2  s  .  com
}

From source file:ca.mudar.snoozy.receiver.PowerConnectionReceiver.java

@Override
public void onReceive(Context context, Intent intent) {

    final Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);

    // Get user preferences
    final SharedPreferences sharedPrefs = context.getSharedPreferences(Const.APP_PREFS_NAME,
            Context.MODE_PRIVATE);
    final SharedPreferences.Editor sharedPrefsEditor = sharedPrefs.edit();
    final boolean hasNotifications = sharedPrefs.getBoolean(Const.PrefsNames.HAS_NOTIFICATIONS, false);
    final boolean hasVibration = (sharedPrefs.getBoolean(Const.PrefsNames.HAS_VIBRATION, false)
            && vibrator.hasVibrator());
    final boolean hasSound = sharedPrefs.getBoolean(Const.PrefsNames.HAS_SOUND, false);
    final boolean onScreenLock = sharedPrefs.getBoolean(Const.PrefsNames.ON_SCREEN_LOCK, true);
    final boolean onPowerLoss = sharedPrefs.getBoolean(Const.PrefsNames.ON_POWER_LOSS, false);
    final int delayToLock = Integer.parseInt(
            sharedPrefs.getString(Const.PrefsNames.DELAY_TO_LOCK, Const.PrefsValues.DELAY_FAST)) * 1000;
    final int notifyCount = sharedPrefs.getInt(Const.PrefsNames.NOTIFY_COUNT, 1);
    final int notifyGroup = sharedPrefs.getInt(Const.PrefsNames.NOTIFY_GROUP, 1);

    final String action = intent.getAction();
    if (action == null)
        return;/*from   w  w  w .  j  a v a 2s .  c  o m*/

    if (action.equals(Const.IntentActions.NOTIFY_DELETE)) {
        if (hasNotifications) {
            // Reset the notification counter (and group) on NOTIFY_DELETE
            sharedPrefsEditor.putInt(Const.PrefsNames.NOTIFY_COUNT, 1);
            sharedPrefsEditor.putInt(Const.PrefsNames.NOTIFY_GROUP, notifyGroup + 1);
            sharedPrefsEditor.apply();
        }
    } else if (action.equals(Intent.ACTION_POWER_CONNECTED)
            || action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
        final boolean isConnectedPower = action.equals(Intent.ACTION_POWER_CONNECTED);

        // Lock the screen, following the user preferences
        if (delayToLock == 0) {
            LockScreenHelper.lockScreen(context, onScreenLock, onPowerLoss, isConnectedPower);
        } else {
            Intent intentService = new Intent(Intent.ACTION_SYNC, null, context, DelayedLockService.class);
            Bundle extras = new Bundle();
            extras.putBoolean(Const.IntentExtras.ON_SCREEN_LOCK, onScreenLock);
            extras.putBoolean(Const.IntentExtras.ON_POWER_LOSS, onPowerLoss);
            extras.putBoolean(Const.IntentExtras.IS_CONNECTED, isConnectedPower);
            extras.putInt(Const.IntentExtras.DELAY_TO_LOCK, delayToLock);
            intentService.putExtras(extras);
            context.startService(intentService);
        }

        // Save in database
        saveHistoryItem(context.getApplicationContext(), isConnectedPower, notifyGroup);

        if (hasNotifications) {
            // Send notification, with sound and vibration
            notify(context, isConnectedPower, hasVibration, hasSound, notifyCount);

            // Increment the notification counter
            sharedPrefsEditor.putInt(Const.PrefsNames.NOTIFY_COUNT, notifyCount + 1);
            sharedPrefsEditor.apply();
        } else {
            // Native Vibration or Sound, without Notifications
            nativeVibrate(context, hasVibration);

            nativeRingtone(context, hasSound);
        }
    }
}

From source file:org.opensilk.music.ui2.LauncherActivity.java

@Override
protected void onStart() {
    super.onStart();
    mPluginConnectionManager.onResume();
    if (RxUtils.notSubscribed(chargingSubscription)) {
        //check if already plugged first
        IntentFilter filter2 = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent battChanged = registerReceiver(null, filter2);
        int battStatus = (battChanged != null) ? battChanged.getIntExtra(BatteryManager.EXTRA_STATUS, -1) : -1;
        if (battStatus == BatteryManager.BATTERY_STATUS_CHARGING
                || battStatus == BatteryManager.BATTERY_STATUS_FULL) {
            keepScreenOn(true);//  ww w.java  2 s . c om
        }
        // keep apprised of future plug events
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_POWER_CONNECTED);
        filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        chargingSubscription = AndroidObservable.fromBroadcast(this, filter).subscribe(new Action1<Intent>() {
            @Override
            public void call(Intent intent) {
                if (Intent.ACTION_POWER_CONNECTED.equals(intent.getAction())) {
                    keepScreenOn(true);
                } else if (Intent.ACTION_POWER_DISCONNECTED.equals(intent.getAction())) {
                    keepScreenOn(false);
                }
            }
        });
    }
}

From source file:org.durka.hallmonitor.CoreReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED) || intent.getAction().equals(QUICKBOOT_POWERON)
            || intent.getAction().equals(HTC_QUICKBOOT_POWERON)) {
        Log.d(LOG_TAG + ".boot", "Boot called.");
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        if (prefs.getBoolean("pref_enabled", false)) {
            Intent mIntent = new Intent(context, CoreService.class);
            context.startService(mIntent);
        }/*from www . ja va2  s  . c  o m*/
    }

    if (CoreStateManager.getInitialized()) {
        localContext = CoreStateManager.getContext();
        mStateManager = ((CoreApp) localContext).getStateManager();
    } else {
        return;
    }

    if (!mStateManager.getPreference().getBoolean("pref_enabled", false)) {
        return;
    }

    mStateManager.acquireCPUGlobal();

    if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {

        Log.d(LOG_TAG + ".screen", "Screen on event received.");

        if (mStateManager.getCoverClosed()) {
            Log.d(LOG_TAG + ".screen", "Cover is closed, display Default Activity.");
            mStateManager.setBlackScreenTime(0);
            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_LAUNCH_ACTIVITY);
            mStateManager.sendToCoreService(mIntent);
        } else {
            // Log.d(LOG_TAG + ".screen",
            // "Cover is open, free everything.");
            // mStateManager.freeDevice();
            Log.d(LOG_TAG + ".screen", "Cover is open, send to background.");
            Intent stbDAIntent = new Intent(CoreApp.DA_ACTION_SEND_TO_BACKGROUND);
            LocalBroadcastManager.getInstance(localContext).sendBroadcastSync(stbDAIntent);
        }

    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        Log.d(LOG_TAG + ".screen", "Screen off event received.");
        // mStateManager.freeDevice();

    } else if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
        Intent batteryDAIntent = new Intent(CoreApp.DA_ACTION_BATTERY_REFRESH);
        LocalBroadcastManager.getInstance(localContext).sendBroadcastSync(batteryDAIntent);

        Intent mIntent = new Intent(localContext, CoreService.class);
        mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_WAKEUP_DEVICE);
        mStateManager.sendToCoreService(mIntent);

    } else if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) {
        Intent batteryDAIntent = new Intent(CoreApp.DA_ACTION_BATTERY_REFRESH);
        LocalBroadcastManager.getInstance(localContext).sendBroadcastSync(batteryDAIntent);

        Intent mIntent = new Intent(localContext, CoreService.class);
        mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_WAKEUP_DEVICE);
        mStateManager.sendToCoreService(mIntent);

    } else if (intent.getAction().equals(ALARM_ALERT_ACTION)) {

        Log.d(LOG_TAG + ".alarm", "Alarm on event received.");

        // only take action if alarm controls are enabled
        if (mStateManager.getPreference().getBoolean("pref_alarm_controls", false)) {

            Log.d(LOG_TAG + ".alarm", "Alarm controls are enabled, taking action.");
            mStateManager.setAlarmFiring(true);

            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_INCOMMING_ALARM);
            mStateManager.sendToCoreService(mIntent);
        } else {
            Log.d(LOG_TAG + ".alarm", "Alarm controls are not enabled.");
        }

    } else if (intent.getAction().equals(ALARM_DONE_ACTION)) {

        Log.d(LOG_TAG + ".alarm", "Alarm done event received.");

        // only take action if alarm controls are enabled
        if (mStateManager.getPreference().getBoolean("pref_alarm_controls", false)) {
            Log.d(mStateManager.getPreference() + ".alarm", "alarm is over, cleaning up");
            mStateManager.setAlarmFiring(false);

            if (mStateManager.getCoverClosed()) {
                Intent mIntent = new Intent(localContext, CoreService.class);
                mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_LAUNCH_ACTIVITY);
                mStateManager.sendToCoreService(mIntent);
            }
        }
    } else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {

        if (mStateManager.getPreference().getBoolean("pref_phone_controls", false)) {
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            Log.d(LOG_TAG + ".phone", "phone state changed to " + state);
            if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                Intent mIntent;
                mStateManager.setPhoneRinging(true);
                mStateManager.setCallFrom(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
                Log.d(LOG_TAG, "call from " + mStateManager.getCallFrom());
                mIntent = new Intent(localContext, CoreService.class);
                mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_INCOMMING_CALL);
                mStateManager.sendToCoreService(mIntent);
            } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                Intent mIntent;
                mStateManager.setPhoneRinging(false);
                Log.d(LOG_TAG, "call is over, cleaning up");
                if (mStateManager.getCoverClosed()) {
                    mIntent = new Intent(localContext, CoreService.class);
                    mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_LAUNCH_ACTIVITY);
                    mStateManager.sendToCoreService(mIntent);
                }
            } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
            }
        } else {
            Log.d(LOG_TAG + ".phone", "phone controls are not enabled");
        }
    } else if (intent.getAction().equals(mStateManager.getActionCover())) {
        int state = intent.getIntExtra(EXTRA_LID_STATE, LID_ABSENT);
        Log.d(LOG_TAG + ".cover", "cover state changed to " + state);
        if (state == LID_CLOSED) {
            Log.d(LOG_TAG + ".cover", "Cover is close, enable Default Activity.");
            mStateManager.setCoverClosed(true);
            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_LAUNCH_ACTIVITY);
            mStateManager.sendToCoreService(mIntent);
        } else if (state == LID_OPEN) {
            // Log.d(LOG_TAG + ".cover",
            // "Cover is open, stopping Default Activity.");
            mStateManager.setCoverClosed(false);
            // mStateManager.freeDevice();
            Log.d(LOG_TAG + ".screen", "Cover is open, send to background.");
            Intent stbDAIntent = new Intent(CoreApp.DA_ACTION_SEND_TO_BACKGROUND);
            LocalBroadcastManager.getInstance(localContext).sendBroadcastSync(stbDAIntent);
            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_WAKEUP_DEVICE);
            mStateManager.sendToCoreService(mIntent);
        }

    } else if (intent.getAction().equals(TORCH_STATE_CHANGED)) {
        if (mStateManager.getPreference().getBoolean("pref_flash_controls", false)) {
            Log.d(LOG_TAG + ".torch", "torch state changed");
            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_TORCH_STATE);
            if (intent.getIntExtra("state", 0) != 0) {
                mIntent.putExtra(CoreApp.CS_EXTRA_STATE, true);
            } else {
                mIntent.putExtra(CoreApp.CS_EXTRA_STATE, false);
            }
            mStateManager.sendToCoreService(mIntent);
        } else {
            Log.d(LOG_TAG + ".torch", "torch controls are not enabled.");
        }

    } else if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
        int state = intent.getExtras().getInt("state");
        Log.d(LOG_TAG + ".headset", "headset is " + (state == 0 ? "gone" : "here") + "!");
        Intent mIntent = new Intent(localContext, CoreService.class);
        mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_HEADSET_PLUG);
        mStateManager.sendToCoreService(mIntent);

    } else if (intent.getAction().equals("org.durka.hallmonitor.debug")) {
        Log.d(LOG_TAG + "", "received debug intent");
        // test intent to show/hide a notification
        boolean showhide = false;
        switch (intent.getIntExtra("notif", 0)) {
        case 1:
            showhide = true;
            break;
        case 2:
            showhide = false;
            break;
        }
        if (showhide) {
            Notification.Builder mBuilder = new Notification.Builder(localContext)
                    .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Hall Monitor")
                    .setContentText("Debugging is fun!");

            NotificationManager mNotificationManager = (NotificationManager) localContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(42, mBuilder.build());
        } else {
            NotificationManager mNotificationManager = (NotificationManager) localContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.cancel(42);
        }
    }
    mStateManager.releaseCPUGlobal();
}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {

    if (intent == null) {
        return START_STICKY;
    }/*from   w  w w  .j  a  v a 2  s.  co m*/

    String action = intent.getAction();

    if (Intent.ACTION_BATTERY_CHANGED.equals(action) || Intent.ACTION_BATTERY_LOW.equals(action)
            || Intent.ACTION_BATTERY_OKAY.equals(action)) {
        // ????

        mHostBatteryManager.setBatteryRequest(intent);

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostBatteryProfile.PROFILE_NAME,
                null, HostBatteryProfile.ATTRIBUTE_ON_BATTERY_CHANGE);
        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostBatteryProfile.setAttribute(mIntent, HostBatteryProfile.ATTRIBUTE_ON_BATTERY_CHANGE);
            Bundle battery = new Bundle();
            HostBatteryProfile.setLevel(battery, mHostBatteryManager.getBatteryLevel());
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    } else if (Intent.ACTION_POWER_CONNECTED.equals(action)
            || Intent.ACTION_POWER_DISCONNECTED.equals(action)) {
        // ????

        mHostBatteryManager.setBatteryRequest(intent);

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostBatteryProfile.PROFILE_NAME,
                null, HostBatteryProfile.ATTRIBUTE_ON_CHARGING_CHANGE);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostBatteryProfile.setAttribute(mIntent, HostBatteryProfile.ATTRIBUTE_ON_CHARGING_CHANGE);
            Bundle charging = new Bundle();

            if (Intent.ACTION_POWER_CONNECTED.equals(action)) {
                HostBatteryProfile.setCharging(charging, true);
            } else {
                HostBatteryProfile.setCharging(charging, false);
            }

            HostBatteryProfile.setBattery(mIntent, charging);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    } else if (action.equals("android.intent.action.NEW_OUTGOING_CALL")) {
        // Phone

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostPhoneProfile.PROFILE_NAME, null,
                HostPhoneProfile.ATTRIBUTE_ON_CONNECT);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostPhoneProfile.setAttribute(mIntent, HostPhoneProfile.ATTRIBUTE_ON_CONNECT);
            Bundle phoneStatus = new Bundle();
            HostPhoneProfile.setPhoneNumber(phoneStatus, intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
            HostPhoneProfile.setState(phoneStatus, CallState.START);
            HostPhoneProfile.setPhoneStatus(mIntent, phoneStatus);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)
            || WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
        // Wifi

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostConnectProfile.PROFILE_NAME,
                null, HostConnectProfile.ATTRIBUTE_ON_WIFI_CHANGE);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostConnectProfile.setAttribute(mIntent, HostConnectProfile.ATTRIBUTE_ON_WIFI_CHANGE);
            Bundle wifiConnecting = new Bundle();
            WifiManager wifiMgr = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
            HostConnectProfile.setEnable(wifiConnecting, wifiMgr.isWifiEnabled());
            HostConnectProfile.setConnectStatus(mIntent, wifiConnecting);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;

    } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostConnectProfile.PROFILE_NAME,
                null, HostConnectProfile.ATTRIBUTE_ON_BLUETOOTH_CHANGE);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostConnectProfile.setAttribute(mIntent, HostConnectProfile.ATTRIBUTE_ON_BLUETOOTH_CHANGE);
            Bundle bluetoothConnecting = new Bundle();
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            HostConnectProfile.setEnable(bluetoothConnecting, mBluetoothAdapter.isEnabled());
            HostConnectProfile.setConnectStatus(mIntent, bluetoothConnecting);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    }
    return super.onStartCommand(intent, flags, startId);
}

From source file:org.mariotaku.twidere.service.RefreshService.java

@Override
public void onCreate() {
    super.onCreate();
    GeneralComponentHelper.build(this).inject(this);
    mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    mPendingRefreshHomeTimelineIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(BROADCAST_REFRESH_HOME_TIMELINE), 0);
    mPendingRefreshMentionsIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(BROADCAST_REFRESH_NOTIFICATIONS), 0);
    mPendingRefreshDirectMessagesIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(BROADCAST_REFRESH_DIRECT_MESSAGES), 0);
    mPendingRefreshTrendsIntent = PendingIntent.getBroadcast(this, 0, new Intent(BROADCAST_REFRESH_TRENDS), 0);
    final IntentFilter refreshFilter = new IntentFilter(BROADCAST_NOTIFICATION_DELETED);
    refreshFilter.addAction(BROADCAST_REFRESH_HOME_TIMELINE);
    refreshFilter.addAction(BROADCAST_REFRESH_NOTIFICATIONS);
    refreshFilter.addAction(BROADCAST_REFRESH_DIRECT_MESSAGES);
    refreshFilter.addAction(BROADCAST_RESCHEDULE_HOME_TIMELINE_REFRESHING);
    refreshFilter.addAction(BROADCAST_RESCHEDULE_MENTIONS_REFRESHING);
    refreshFilter.addAction(BROADCAST_RESCHEDULE_DIRECT_MESSAGES_REFRESHING);
    registerReceiver(mStateReceiver, refreshFilter);
    final IntentFilter batteryFilter = new IntentFilter();
    batteryFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    batteryFilter.addAction(Intent.ACTION_BATTERY_OKAY);
    batteryFilter.addAction(Intent.ACTION_BATTERY_LOW);
    batteryFilter.addAction(Intent.ACTION_POWER_CONNECTED);
    batteryFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    final IntentFilter screenFilter = new IntentFilter();
    screenFilter.addAction(Intent.ACTION_SCREEN_ON);
    screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
    screenFilter.addAction(Intent.ACTION_USER_PRESENT);
    registerReceiver(mPowerStateReceiver, batteryFilter);
    registerReceiver(mScreenStateReceiver, screenFilter);
    PowerStateReceiver.setServiceReceiverStarted(true);
    if (Utils.hasAutoRefreshAccounts(this)) {
        startAutoRefresh();/*ww  w.j ava  2 s  . co  m*/
    } else {
        stopSelf();
    }
}

From source file:org.proninyaroslav.libretorrent.services.TorrentTaskService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        ArrayList<String> ids = intent.getStringArrayListExtra(TorrentTaskServiceIPC.TAG_TORRENT_IDS_LIST);

        if (ids != null) {
            List<Torrent> torrents = new ArrayList<>();

            for (String id : ids) {
                torrents.add(repo.getTorrentByID(id));
            }/*  w w w . j  a  v  a 2s.co  m*/

            addTorrents(torrents);
        }
    }

    if (isAlreadyRunning) {
        if (intent != null && intent.getAction() != null) {
            switch (intent.getAction()) {
            case NotificationReceiver.NOTIFY_ACTION_SHUTDOWN_APP:
                ipc.sendTerminateAllClients(clientCallbacks);
                clientCallbacks.clear();
                stopForeground(true);
                stopSelf(startId);
                break;
            case Intent.ACTION_BATTERY_LOW:
                if (pref.getBoolean(getString(R.string.pref_key_battery_control), false)) {
                    pauseTorrents.set(true);
                    pauseAll();
                }
                break;
            case Intent.ACTION_BATTERY_OKAY:
                if (pref.getBoolean(getString(R.string.pref_key_battery_control), false)
                        && !pref.getBoolean(getString(R.string.pref_key_download_and_upload_only_when_charging),
                                false)) {
                    pauseTorrents.set(false);
                    resumeAll();
                }
                break;
            case Intent.ACTION_POWER_CONNECTED:
                if (pref.getBoolean(getString(R.string.pref_key_download_and_upload_only_when_charging),
                        false)) {
                    pauseTorrents.set(false);
                    resumeAll();
                }
                break;
            case Intent.ACTION_POWER_DISCONNECTED:
                if (pref.getBoolean(getString(R.string.pref_key_download_and_upload_only_when_charging),
                        false)) {
                    pauseTorrents.set(true);
                    pauseAll();
                }
                break;
            }
        }

        return START_STICKY;
    }

    /* The first start */
    isAlreadyRunning = true;

    makeForegroundNotify();
    startUpdateForegroundNotify();

    return START_STICKY;
}

From source file:saphion.services.ForegroundService.java

protected void triggerFunc(String action) {
    if (action == Intent.ACTION_SCREEN_OFF) {
        PowerProfItems pItems = PowerPreference.retPower(getBaseContext())
                .get(mPref.getInt(PreferenceHelper.POSITIONS, 0));
        if (pItems.getData()) {
            if (pItems.getS_Off_mdata()) {
                mVal = pItems.getS_Off_int_mdata();

                if (ToggleHelper.isDataEnable(getBaseContext())) {
                    try {
                        ToggleHelper.toggleMData(getBaseContext());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }/*from   ww  w . j a v  a  2 s.c om*/

                }
                if (mVal != -99) {
                    Log.d("Posting dataOnRunnable with mVal: " + mVal + " and millies of "
                            + (mVal * 60 * 1000));
                    handler.postDelayed(dataOnRunnable, mVal * 60 * 1000);
                } else {
                    Log.d("Won't post because mVal is: " + mVal);
                }
            }
        }
        if (pItems.getWifi()) {
            if (pItems.getS_Off_wifi()) {
                wVal = pItems.getS_Off_int_wifi();
                if (ToggleHelper.isWifiEnabled(getBaseContext())) {

                    ToggleHelper.toggleWifi(getBaseContext());

                }
                if (wVal != -99)
                    handler.postDelayed(wifiOnRunnable, wVal * 60 * 1000);
            }
        }
    } else if (action == Intent.ACTION_SCREEN_ON) {
        PowerProfItems pItems = PowerPreference.retPower(getBaseContext())
                .get(mPref.getInt(PreferenceHelper.POSITIONS, 0));
        handler.removeCallbacks(dataOffRunnable);
        handler.removeCallbacks(dataOnRunnable);
        handler.removeCallbacks(wifiOffRunnable);
        handler.removeCallbacks(wifiOnRunnable);
        if (pItems.getData()) {
            if (pItems.getS_Off_mdata()) {
                if (!ToggleHelper.isDataEnable(getBaseContext())) {
                    try {
                        ToggleHelper.toggleMData(getBaseContext());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (pItems.getWifi()) {
            if (pItems.getS_Off_wifi()) {
                if (!ToggleHelper.isWifiEnabled(getBaseContext())) {

                    ToggleHelper.toggleWifi(getBaseContext());

                }
            }
        }
    }

    // Average stats processing

    // Log.Toast(getBaseContext(), "Recieved action", Toast.LENGTH_LONG);

    mPref = getSharedPreferences(PREF_NAME, MODE_MULTI_PROCESS);
    Editor mPrefEditor = mPref.edit();
    Status mStat = readBatteryStat();
    if ((mStat.getConnected() && mStat.getLevel() == 100) || action == Intent.ACTION_POWER_DISCONNECTED) {

        // Log.Toast(getBaseContext(), "Disconnected", Toast.LENGTH_LONG);
        int diff;
        if ((diff = mStat.getLevel()
                - mPref.getInt(PreferenceHelper.STAT_CONNECTED_LAST_LEVEL, mStat.getLevel())) > 3) {
            calcStat(mStat, mPref, mPrefEditor, diff, true);
        }

        if (mPref.getInt(PreferenceHelper.STAT_DISCONNECTED_LAST_LEVEL, -99) == -99 || diff < 3) {
            mPrefEditor.putInt(PreferenceHelper.STAT_DISCONNECTED_LAST_LEVEL, mStat.getLevel());
            mPrefEditor.putString(PreferenceHelper.STAT_DISCONNECTED_LAST_TIME,
                    TimeFuncs.getCurrentTimeStamp());
        }

    }

    if ((!mStat.getConnected() && mStat.getLevel() <= 1) || action == Intent.ACTION_POWER_CONNECTED) {

        // Log.Toast(getBaseContext(), "Connected", Toast.LENGTH_LONG);

        int diff;
        if ((diff = mPref.getInt(PreferenceHelper.STAT_DISCONNECTED_LAST_LEVEL, mStat.getLevel())
                - mStat.getLevel()) > 3) {
            calcStat(mStat, mPref, mPrefEditor, diff, false);
        }

        if (mPref.getInt(PreferenceHelper.STAT_CONNECTED_LAST_LEVEL, -99) == -99 || diff < 3) {
            mPrefEditor.putInt(PreferenceHelper.STAT_CONNECTED_LAST_LEVEL, mStat.getLevel());
            mPrefEditor.putString(PreferenceHelper.STAT_CONNECTED_LAST_TIME, TimeFuncs.getCurrentTimeStamp());
        }
    }

    mPrefEditor.commit();

}

From source file:org.restcomm.app.qoslib.Services.Intents.IntentHandler.java

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Bundle intentExtras = intent.getExtras();

    if (owner == null)
        return;//w ww .ja  v a  2 s  .com
    owner.getWebSocketManager().sendIntentToWebSocket(action, intentExtras);

    //capture the "battery changed" event
    if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        DeviceInfoOld.battery = level * 100 / scale;
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean bCharging = plugged == BatteryManager.BATTERY_PLUGGED_AC
                || plugged == BatteryManager.BATTERY_PLUGGED_USB;
        owner.setBatteryCharging(bCharging);
        dataMonitorStats.setBattery(bCharging, DeviceInfoOld.battery);
    } else if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
        owner.setBatteryCharging(true);
        dataMonitorStats.setBattery(true, null);
    } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
        owner.setBatteryCharging(false);
        dataMonitorStats.setBattery(false, null);
    } else if (action.equals(Intent.ACTION_VIEW)) {
        //this is supposed to trigger the update event
        //owner.triggerUpdateEvent(false, false);
    } else if (action.equals(CommonIntentActionsOld.ACTION_START_UI)) {
        String packagename = intent.getStringExtra("packagename");
        String mypackagename = context.getPackageName();
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putString(PreferenceKeys.Miscellaneous.YEILDED_SERVICE, packagename).commit();
        // If the UI started on a different MMC app UI, then we stop this service until this UI is launched
        if (!packagename.equals(mypackagename)) // This will exit the service when safe, and won't restart it because it will be yeilded
            owner.restartSelf();
    } else if (action.equals(UPDATE_ACTION)) {
        owner.getEventManager().triggerUpdateEvent(false, false);
    } else if (action.equals(COLDRESET_ACTION)) {
        //this is supposed to trigger the update event
        owner.getGpsManager().coldStart("triggered by user");
    } else if (action.equals(EMAIL_CSV)) {
        //this is supposed to trigger the update event
        owner.requestCsvEmail();
    } else if (action.equals(SPEED_TEST)) {
        //this is supposed to trigger a speed test
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        //owner.triggerSMSTest(trigger);
        owner.getEventManager().queueActiveTest(EventType.MAN_SPEEDTEST, trigger);
    } else if (action.equals(RUN_WEBSOCKET)) {
        //this is supposed to trigger a speed test
        boolean bStart = intent.getBooleanExtra(EXTRA_START_WEBSOCKET, true);
        owner.getWebSocketManager().runWebSocket(bStart);
        //owner.triggerSpeedTest(trigger);
    } else if (action.equals(ACTIVE_TEST)) {
        //this is supposed to trigger a speed test
        int evType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0);
        EventType eventType = EventType.get(evType);
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        owner.getEventManager().queueActiveTest(eventType, trigger);
    } else if (action.equals(SMS_TEST)) {
        //this is supposed to trigger a speed test
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        //owner.triggerSMSTest(trigger);
        owner.getEventManager().queueActiveTest(EventType.SMS_TEST, trigger);
    } else if (action.contains(SMS_DELIVERED)) {
        //add delivery time to connection history

        int identifier = intent.getIntExtra("identifier", 0); //in case we need to search connection list to find which SMS
        long deliveryTime = 0;

        switch (getResultCode()) {
        case Activity.RESULT_OK:
            deliveryTime = System.currentTimeMillis();
            break;
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
            deliveryTime = -1;
            break;
        case SmsManager.RESULT_ERROR_NO_SERVICE:
            deliveryTime = -1;
            break;
        case SmsManager.RESULT_ERROR_NULL_PDU:
            deliveryTime = -1;
            break;
        case SmsManager.RESULT_ERROR_RADIO_OFF:
            deliveryTime = -1;
            break;
        }

        owner.getEventManager().handleSMSDeliverNotification(identifier, deliveryTime);
    } else if (action.equals(LATENCY_TEST)) {
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        owner.getEventManager().queueActiveTest(EventType.LATENCY_TEST, trigger);
        //owner.runLatencyTest(false);
    } else if (action.equals(ACTION_STOP_SPEEDTEST)) {
        owner.getEventManager().killSpeedTest();
    } else if (action.equals(ACTION_STOP_VIDEOTEST)) {
        int testType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0);
        owner.getEventManager().killActiveTest(testType);
    } else if (action.equals(ROAMING_ON)) {
        dataMonitorStats.setRoaming(true);
    } else if (action.equals(ROAMING_OFF)) {
        dataMonitorStats.setRoaming(false);
    } else if (action.equals("android.intent.action.ANY_DATA_STATE")) {
        String apn = intentExtras.getString("apn");
        String state = intentExtras.getString("state");
        String apnType = intentExtras.getString("apnType");
        String extras = apnType + "" + state;
        if (state.equals("CONNECTED") && !apnType.equals("default"))
            extras = extras + "!";
        if (apnType != null && apnType.equals("default") && apn != null) {
            SharedPreferences securePref = MainService.getSecurePreferences(context);
            securePref.edit().putString(PreferenceKeys.Miscellaneous.KEY_APN, apn).commit();
        }

    } else if (action.equals("android.intent.action.DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN")) {
        String apn = intentExtras.getString("apn");
        String apnType = intentExtras.getString("apnType");
        String extras = apn + "," + apnType;
    } else if (action.equals("android.intent.action.ACTION_DATA_CONNECTION_FAILED")) {
        String phoneName = intentExtras.getString("phoneName");
        String reason = intentExtras.getString("reason");
        String extras = phoneName + "," + reason;
    } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        if (owner.getUsageLimits().getDormantMode() > 0)
            return;
        // wifi state change may trigger the event queue to be sent
        //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "NETWORK_STATE_CHANGED_ACTION", "");
        owner.wifiStateChange((NetworkInfo) intentExtras.getParcelable(WifiManager.EXTRA_NETWORK_INFO));
        owner.trackAccessPoints(0);
        dataMonitorStats.setWifi(PhoneState.isNetworkWifi(owner));
    } else if (action.equals(WIMAX_STATE_CHANGE)) {
        owner.trackAccessPoints(0);
    } else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
        //         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //         BluetoothClass bclass = device.getBluetoothClass();
        //         int major = bclass.getMajorDeviceClass();
        //         if (major == 1024)
        //            owner.setBTHeadsetState(1);
        //         owner.trackAccessPoints();
    } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)) {
        owner.trackAccessPoints(0);
    } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
        //         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //         BluetoothClass bclass = device.getBluetoothClass();
        //         int major = bclass.getMajorDeviceClass();
        //         if (major == 1024)
        //            owner.setBTHeadsetState(0);
        //         owner.trackAccessPoints();
    } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
        try {
            int state = intent.getIntExtra("state", -1);
            owner.setHeadsetState(state);
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive",
                    "error receiving Intent.ACTION_HEADSET_PLUG: " + e);
        }
    } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
        int state = intent.getIntExtra("state", -1);
        owner.setHeadsetState(state);
    } else if (action.equals(CommonIntentActionsOld.ACTION_START_VOICETEST)) {
        //this is supposed to trigger a speed test
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_VQ_TRIGGER, 0);
        owner.getVQManager().runTest(trigger);
    } else if (action.equals(CommonIntentActionsOld.ACTION_TEST_VQ_DEVICE)) {
        owner.getVQManager().runTest(10);
    } else if (action.equals(CommonIntentActionsOld.ACTION_STOP_VOICETEST)) {
        owner.getVQManager().killTest();
    } else if (action.equals(RESTART_MMC_SERVICE)) {
        owner.restartNextIdle();

    } else if (action.equals(STOP_TRACKING_ACTION)) {
        owner.getEventManager().stopTracking();
    } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
        try {
            dataMonitorStats.setScreen(false);
            SignalEx mmcSignal = new SignalEx();
            owner.getPhoneStateListener().processNewMMCSignal(mmcSignal);
            if (owner.getTravelDetector() != null) {
                owner.getPhoneState().screenChanged(false);
                owner.getEventManager().screenChanged(false);
            }
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive",
                    "received action SCREEN_OFF, calling MainService.processNewMMCSignal()", e);
        }
    } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
        dataMonitorStats.setScreen(true);
        if (owner.getTravelDetector() != null) {
            owner.getPhoneState().screenChanged(true);
            owner.getEventManager().screenChanged(true);
        }
    } else if (action.equals(ACTION_ALARM_MINUTE)) {
        // CPU wakes very briefly only in order to spur cellid updates
        owner.getTravelDetector().triggerTravelCheck();
        QosAPI.checkHostApp(context);
    } else if (action.equals(ACTION_TRACKING_5MINUTE)) {
        owner.getTrackingManager().runTracking();
    } else if (action.equals(ACTION_TRACKING_1MINUTE)) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "ACTION_TRACKING_1MINUTE");
        owner.getTrackingManager().runTrackingTests();
    } else if (action.equals(ACTION_ALARM_3HOUR)) {
        dataMonitorStats.prepareAllStatistics();
        owner.getEventManager().triggerUpdateEvent(true, false);
        //         Calendar cal = Calendar.getInstance(); 
        //          int hour = cal.get (Calendar.HOUR_OF_DAY); 
        //         //If 12pm to 3 am
        //          if(((hour >= 0 && hour <= 3) || hour == 24) && owner.isNetworkWifi()) {
        //            //See if transit info needs to be downloaded
        //             
        //             //Don't allow the app to shut down until the work is done, keep the CPU running
        //             MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_ALARM_3HOUR, wakelock turned on and checking transit "
        //                   + "info uptodate at 24-hour: " + hour);
        //             wakeLock.acquire();
        //             
        //             downloadAreasIfOutOfDate();
        //          }
    }
    //      else if(action.equals(ACTION_TRANSIT_DL_DONE)) {
    //         //Allow CPU to move on
    //         if(wakeLock != null) {
    //            wakeLock.release(); 
    //            MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "received action ACTION_TRANSIT_DONE, wakelock turned off");
    //         }
    //      }
    //      else if(action.equals(ACTION_TRANSIT_DL_START)) {
    //         //Don't allow the app to shut down until the work is done, keep the CPU running
    //          MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_TRANSIT_DL_START, wakelock turned on and downloading transit if was requested");
    //          wakeLock.acquire();
    //          
    //          downloadAreasIfOutOfDate();
    //      }
    else if (action.equals(ACTION_ALARM_SCANAPPS)) {
        int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner)
                .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0);
        // run datamonitor if enabled
        if (intervalDM > 0) {
            dataMonitorStats.scanApps();
            dataMonitorStats.getRunningAppsString(false); // for debug
        }

        // Also using this timer for GCM heartbeats (its a 5 minute heartbeat to tell Google Cloud Messaging to check the socket more often for more reliable push messages)
        // 2 independent timers might wake up device twice as often, doubling the battery impact, so I'm forcing it to use one for both cases
        //         boolean useHeartbeat = PreferenceManager.getDefaultSharedPreferences(owner).getBoolean("KEY_GCM_HEARTBEAT", false);
        //         if (useHeartbeat) {
        //            GcmKeepAlive gcm = new GcmKeepAlive(owner);
        //            gcm.broadcastIntents();
        //         }
    } else if (action.equals(ACTION_ALARM_15MINUTE)) {

        int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner)
                .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0);
        // run datamonitor if enabled
        if (intervalDM > 0) {
            boolean firstBucketDone = PreferenceManager.getDefaultSharedPreferences(owner)
                    .getBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, false);
            if (!firstBucketDone) { //if false, first bucket needs to be done
                dataMonitorStats.firstBucket();
                dataMonitorStats.monitor();
                PreferenceManager.getDefaultSharedPreferences(owner).edit()
                        .putBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, true).commit();
                LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, "MMCIntentHandlerOld", "onReceive",
                        "First bucket at: " + System.currentTimeMillis() / 1000);
            } else {
                dataMonitorStats.monitor();
                //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "onReceive", "15 min bucket at: " + System.currentTimeMillis()/1000);
            }
        }
        // regardless, still make sure GPS is idle unless needed
        owner.getGpsManager().safeguardGps();
    } else if (action.equals(GPS_STATE_ON)) {
        dataMonitorStats.setGps(true);
    } else if (action.equals(GPS_STATE_OFF)) {
        dataMonitorStats.setGps(false);
    } else if (action.equals(PHONE_CALL_CONNECT)) {
        dataMonitorStats.setPhone(true);
    } else if (action.equals(PHONE_CALL_DISCONNECT)) {
        dataMonitorStats.setPhone(false);
    } else if (action.equals(HANDOFF)) {
        dataMonitorStats.handoff();
    } else if (action.equals(MANUAL_TRANSIT_START)) {
        long lat = intent.getIntExtra("latitude", 0);
        long lon = intent.getIntExtra("longitude", 0);
        Location location = new Location("");
        location.setLatitude(lat / 1000000.0);
        location.setLongitude(lon / 1000000.0);
        location.setAccuracy(-3);

        //         PreferenceManager.getDefaultSharedPreferences(owner).edit().putString(
        //                PreferenceKeys.Miscellaneous.SURVEY_COMMAND,).commit();
        PreferenceManager.getDefaultSharedPreferences(owner).edit()
                .putString("transitEvent", String.valueOf(lat) + "," + String.valueOf(lon)).commit();
        reportManager.manualTransitEvent = owner.getEventManager().triggerSingletonEvent(EventType.MAN_TRANSIT);
        reportManager.manualTransitEvent.setLocation(location, 0);
        owner.getTravelDetector().setTravelling(false);
    } else if (action.equals(MANUAL_TRANSIT_END)) {
        if (reportManager.manualTransitEvent == null)
            return;
        String accelData = intent.getStringExtra("accelerometer");
        int stationFrom = intent.getIntExtra("stationFrom", 0);
        int stationTo = intent.getIntExtra("stationTo", 0);
        int duration = intent.getIntExtra("duration", 0);
        int corrected = intent.getIntExtra("corrected", 0);
        if (corrected != 0) {
            Location location = reportManager.manualTransitEvent.getLocation();
            location.setAccuracy(-4);
        }

        reportManager.manualTransitEvent.setAppData(accelData); //TODO want this to really be in appdata?
        reportManager.manualTransitEvent.setLookupid1(stationFrom);
        reportManager.manualTransitEvent.setLookupid2(stationTo);
        reportManager.manualTransitEvent.setDuration(duration);
        owner.getEventManager().unstageAndUploadEvent(reportManager.manualTransitEvent, null);
        reportManager.manualTransitEvent = null;
    } else if (action.equals(MANUAL_TRANSIT_CANCEL)) {
        if (reportManager.manualTransitEvent != null) {
            owner.getEventManager().unstageEvent(reportManager.manualTransitEvent);
            ReportManager reportManager = ReportManager.getInstance(owner);
            reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(),
                    "timestamp > ? And accuracy = 3",
                    new String[] { String.valueOf(reportManager.manualTransitEvent.getEventTimestamp()) });
            reportManager.manualTransitEvent = null;
        }
    } else if (action.equals(MANUAL_PLOTTING_START)) {
        int floor = intent.getIntExtra("floor", 0);
        //         int type = intent.getIntExtra("type", -1);  //1(indoor) or 2(outdoor)
        int topFloor = intent.getIntExtra("top", -1);
        int lat = intent.getIntExtra("latitude", -1);
        int lng = intent.getIntExtra("longitude", -1);
        long osm_id = intent.getLongExtra("osm_id", 0);
        String poly = intent.getStringExtra("poly");

        reportManager.manualPlottingEvent = owner.getEventManager()
                .triggerSingletonEvent(EventType.MAN_PLOTTING);
        reportManager.manualPlottingEvent.setEventIndex(floor);
        reportManager.manualPlottingEvent.setDuration(topFloor);
        reportManager.manualPlottingEvent.setBuildingID(osm_id);
        reportManager.manualPlottingEvent.setAppData(poly);
        Location location = new Location("");
        location.setLatitude(lat / 1000000.0);
        location.setLongitude(lng / 1000000.0);
        location.setAccuracy(-1);
        reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "latitude",
                Double.toString(location.getLatitude()));
        reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "longitude",
                Double.toString(location.getLongitude()));

        reportManager.manualPlottingEvent.setLocation(location, 0);
        presetEventId(reportManager.manualPlottingEvent); // reserve an EventID for this manual sampling event, to be used for Share links

        owner.getTravelDetector().setTravelling(false);
    } else if (action.equals(MANUAL_PLOTTING_END)) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "MANUAL_PLOTTING_END");
        //         owner.getEventManager().unstageEvent(manulaPlottingEvent); //does not upload
        if (reportManager.manualPlottingEvent != null)
            owner.getEventManager().unstageAndUploadEvent(reportManager.manualPlottingEvent, null);
        //After the event was submitted, reset it so we don't restore an old event in ManualMapping
        reportManager.manualPlottingEvent = null;
    } else if (action.equals(MANUAL_PLOTTING_CANCEL)) {
        if (reportManager.manualPlottingEvent != null) {
            reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(),
                    "timestamp > ? And accuracy < 0",
                    new String[] { String.valueOf(reportManager.manualPlottingEvent.getEventTimestamp()) });
            reportManager.manualPlottingEvent = null;

        }
    }
    //      else if(intent.getAction().equals(MMS_RECEIVED)) {
    //         LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_RECEIVED", intentExtras.toString());
    //      }
    //      else if(intent.getAction().equals(MMS_SENT)) {
    //         LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_SENT", intentExtras.toString());
    //      }
    //      else if(intent.getAction().equals(SMS_REJECTED)) {
    //         LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived SMS_REJECTED", intentExtras.toString());
    //      }
    else if (intent.getAction().equals(SMS_RECEIVED)) {
        SmsMessage[] msgs = null;
        //         String msg_from;
        if (intentExtras == null)
            return;

        Object[] pdus = (Object[]) intentExtras.get("pdus");
        msgs = new SmsMessage[pdus.length];
        String[] msgBody = new String[msgs.length];
        for (int i = 0; i < msgs.length; i++) {
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            //            msg_from = msgs[i].getOriginatingAddress();
            String msg = msgs[i].getMessageBody().trim();
            if (msg.length() > 10) {
                msg = msg.substring(1, msg.length() - 1);
                msg = "{" + msg + "}";
            }

            msgBody[i] = msg;

        }
        handleCommands(msgBody, true, 0);
    } else if (action.equals(VIEWING_SIGNAL)) {
        owner.setEnggQueryTime();
    } else if (intent.getAction().equals(SURVEY)) {
        if (intentExtras == null)
            return;

        int surveyid = intentExtras.getInt(SURVEY_EXTRA);
        postSurvey(surveyid);
    } else if (intent.getAction().equals(GCM_MESSAGE)) {
        if (intentExtras == null)
            return;
        try {
            String msg = intentExtras.getString(GCM_MESSAGE_EXTRA);
            long starttime = intentExtras.getLong("GCM_STARTTIME_EXTRA");
            EventResponse eventResponse = gson.fromJson(msg, EventResponse.class);
            eventResponse.init();
            eventResponse.setStartTime(starttime);
            eventResponse.handleEventResponse(owner, true);
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceived GCM_MESSAGE", "exception", e);
        }
    } else if (intent.getAction().equals(COMMAND)) {
        if (intentExtras == null)
            return;

        String commands = intentExtras.getString(COMMAND_EXTRA);
        if (commands == null)
            return;
        long starttime = intent.getLongExtra("STARTTIME_EXTRA", 0);
        String[] msgs = null;
        try {
            JSONArray cmds = new JSONArray(commands);
            msgs = new String[cmds.length()];
            for (int j = 0; j < cmds.length(); j++)
                msgs[j] = cmds.getJSONObject(j).toString();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        //commands = commands.replace("[", "");
        //commands = commands.replace("]", "");
        //String msgs[] = commands.split("/");
        handleCommands(msgs, false, starttime);
    }

    else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
        int val = 0;
        val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1);
        String msg = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE");
        String msg2 = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_MESSAGE");
        //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "String CALL_DISCONNECT_CAUSE", msg);
        //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "Int CALL_DISCONNECT_CAUSE", ""+val);
    } else if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
        String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        //if (phoneNumber != null)
        //    MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "NEW_OUTGOING_CALL", phoneNumber);
    }

    else if (intent.getAction().equals("android.intent.action.PRECISE_CALL_STATE")) {
        int val = 0;
        //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1);
        int state_ringing = intent.getIntExtra("ringing_state", -1);
        int state_foreground = intent.getIntExtra("foreground_state", -1);
        int state_background = intent.getIntExtra("background_state", -1);

        int disconnect_cause = intent.getIntExtra("disconnect_cause", -1);
        int precise_disconnect_cause = intent.getIntExtra("precise_disconnect_cause", -1);
        PreciseCallCodes precisecall = new PreciseCallCodes(state_ringing, state_foreground, state_background,
                disconnect_cause, precise_disconnect_cause);
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "PRECISE_CALL_STATE", precisecall.toString());
        owner.getPhoneStateListener().onPreciseCallState(precisecall);
    } else if (intent.getAction().equals("android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED")) {
        int val = 0;
        //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1);
        int state = intent.getIntExtra("state", -1);
        int networkType = intent.getIntExtra("networkType", -1);
        String reason = intent.getStringExtra("reason");
        String failCause = intent.getStringExtra("failCause");
        String apnType = intent.getStringExtra("apnType");
        String apn = intent.getStringExtra("apn");
        Object linkProperties = intent.getParcelableExtra("linkProperties");
        if (!apnType.equals("default"))
            return;
        //         if (failCause != null && failCause.length() > 0)
        //         {
        //            String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause);
        //            MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            if (linkProperties != null)
        //            {
        //               msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED  linkProperties:%s", linkProperties.toString());
        //               MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            }
        //         }
        //         else if (reason != null && reason.length() > 0)
        //         {
        //            String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause);
        //            MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            if (linkProperties != null)
        //            {
        //               msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED  linkProperties:%s", linkProperties.toString());
        //               MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            }
        //         }
    } else if (intent.getAction().equals("org.restcomm.android.CONNECT_FAILED")
            || intent.getAction().equals("org.restcomm.android.CALL_STATE")
            || intent.getAction().equals("org.restcomm.android.DISCONNECT_ERROR")) {
        owner.getPhoneStateListener().getRestCommManager().handleIntent(owner, intent);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_DISCONNECT)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String cause = intent.getStringExtra(EXTRA_RADIOLOG_DISC_CAUSE);
        owner.getPhoneStateListener().onDisconnect(time, cause);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_CONNECT)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String state = intent.getStringExtra(EXTRA_RADIOLOG_CONN_STATE);
        owner.getPhoneStateListener().onConnect(time, state);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_NEIGHBORS)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String neighbors = intent.getStringExtra(EXTRA_RADIOLOG_NEIGHBORS);
        //owner.onConnect(time, state);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMODE)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String jsonstr = intent.getStringExtra(EXTRA_RADIOLOG_SVC_JSON);
        JSONObject json = null;
        try {
            json = new JSONObject(jsonstr);
        } catch (Exception e) {
        }
        String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT);
        String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME);
        owner.getPhoneStateListener().onServiceMode(time, json, values, name);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMENU)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT);
        String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME);
        owner.getPhoneStateListener().onServiceMenu(time, values, name);
    } else if (intent.getAction().equals(ACTION_MMCSYS_VERSION)) {
        Integer version = intent.getIntExtra(EXTRA_MMCSYS_VERSION, 0);
        owner.onSvcModeVersion(version);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_ERROR)) {
        String error = intent.getStringExtra(EXTRA_RADIOLOG_ERROR);
        String details = intent.getStringExtra(EXTRA_RADIOLOG_ERROR_DETAIL);
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, "RilReader", error, details);
        //owner.onConnect(time, state);
    }

}

From source file:saphion.services.ForegroundService.java

@SuppressWarnings("deprecation")
@Override//from   w  ww. jav a 2s.  c  om
public void onCreate() {

    mPref = ForegroundService.this.getSharedPreferences(PREF_NAME, MODE_MULTI_PROCESS);

    // receive ACTION_BATTERY_CHANGED.
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_BATTERY_CHANGED);
    filter.addAction(Intent.ACTION_POWER_CONNECTED);
    filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intents.MYBAT_INTENT);
    filter.addAction(Intents.TORCH_ON);
    filter.addAction(Intents.TORCH_OFF);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
        filter.addAction(Intents.SWITCHER_INTENT);
        filter.addAction(Intents.SWITCHER_NOTI);
        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
    }
    registerReceiver(mBroadcastReceiver, filter);

    readbattery();

    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (!mPref.getBoolean(PreferenceHelper.NOTIFICATION_ENABLE, true)) {
        mNM.cancelAll();// .notify(id, notification);

    }
    try {
        mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature);
        mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature);
        return;
    } catch (NoSuchMethodException e) {
        // Running on an older platform.
        mStartForeground = mStopForeground = null;
    }
    try {
        mSetForeground = getClass().getMethod("setForeground", mSetForegroundSignature);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException("OS doesn't have Service.startForeground OR Service.setForeground!");
    }
}