Example usage for android.app Service START_STICKY

List of usage examples for android.app Service START_STICKY

Introduction

In this page you can find the example usage for android.app Service START_STICKY.

Prototype

int START_STICKY

To view the source code for android.app Service START_STICKY.

Click Source Link

Document

Constant to return from #onStartCommand : if this service's process is killed while it is started (after returning from #onStartCommand ), then leave it in the started state but don't retain this delivered intent.

Usage

From source file:net.texh.cordovapluginstepcounter.StepCounterService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "onStartCommand");

    SharedPreferences sharedPref = getSharedPreferences(CordovaStepCounter.USER_DATA_PREF,
            Context.MODE_PRIVATE);
    Boolean pActive = CordovaStepCounter.getPedometerIsActive(sharedPref);

    //Service should not be activated (pedometer stopped by user)
    if (!pActive) {
        Log.i(TAG,//from   ww  w .j a va 2  s .co  m
                "/!\\ onStartCommand Ask to stopSelf, should not be launched ! Should not even be here (maybe 4.4.2 specific bug causes a restart here)");
        stopSelf();
        return START_NOT_STICKY;
    }

    Log.i(TAG, "- Relaunch service in 1 hour (4.4.2 start_sticky bug ) : ");
    Intent newServiceIntent = new Intent(this, StepCounterService.class);
    AlarmManager aManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent stepIntent = PendingIntent.getService(getApplicationContext(), 10, newServiceIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    //PendingIntent.GetService (ApplicationContext, 10, intent2, PendingIntentFlags.UpdateCurrent);
    aManager.set(AlarmManager.RTC, java.lang.System.currentTimeMillis() + 1000 * 60 * 60, stepIntent);

    if (isRunning /* || has no step sensors */) {
        Log.i(TAG, "Not initialising sensors");
        return Service.START_STICKY;
    }

    Log.i(TAG, "Initialising sensors");
    doInit();

    isRunning = true;
    return Service.START_STICKY;
}

From source file:com.rareventure.gps2.GpsTrailerService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    /* ttt_installer:remove_line */Log.d(GTG.TAG, "Starting on intent " + intent);
    //if we were already running and had a gpsManager, notify that we woke up
    if (gpsManager != null)
        gpsManager.notifyWoken();/*from  w w w. ja va  2 s  .  c  om*/

    mHandler = new Handler();

    GTG.service = this;

    //we want our service to restart if stopped because of memory constraints or whatever else
    return Service.START_STICKY;
}

From source file:com.google.android.apps.santatracker.cast.DataCastNotificationService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    LOGD(TAG, "onStartCommand");
    if (intent != null) {

        String action = intent.getAction();
        if (ACTION_VISIBILITY.equals(action)) {
            mVisible = intent.getBooleanExtra(NOTIFICATION_VISIBILITY, false);
            LOGD(TAG, "onStartCommand(): Action: ACTION_VISIBILITY " + mVisible);
            if (mNotification == null) {
                setUpNotification();//from  w w  w  .  j a  v  a 2 s . c o m
            }
            if (mVisible && mNotification != null) {
                startForeground(NOTIFICATION_ID, mNotification);
            } else {
                stopForeground(true);
            }
        } else {
            LOGD(TAG, "onStartCommand(): Action: none");
        }

    } else {
        LOGD(TAG, "onStartCommand(): Intent was null");
    }

    return Service.START_STICKY;
}

From source file:org.freedesktop.geoclueshare.LocationService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "Service started");
    createNotification();/*from www  .  j  a  va  2s .  com*/

    Zeroconf.attainLock(this);

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    deviceId = Settings.Secure.getString(getApplicationContext().getContentResolver(),
            Settings.Secure.ANDROID_ID);

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
            case MESSAGE_START_GPS:
                startGps();
                Log.d(TAG, "GPS start");
                Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                if (loc != null && System.currentTimeMillis() - loc.getTime() > LAST_KNOWN_LOCATION_MAX_AGE)
                    loc = null;

                if (loc != null)
                    NetworkListener.sendData(getGgaFromLocation(loc));
                break;
            case MESSAGE_STOP_GPS:
                stopGps();
                Log.d(TAG, "GPS stop");
            }
        }
    };

    networkListener = new NetworkListener(handler);
    networkListener.execute();

    return Service.START_STICKY;
}

From source file:com.avalond.ad_blocak.vpn.AdVpnService.java

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
    Log.i(TAG, "onStartCommand");
    switch (intent == null ? Command.START
            : Command.values()[intent.getIntExtra("COMMAND", Command.START.ordinal())]) {
    case START://from  w  ww. j  a  v  a 2  s  .  co m
        startVpn(intent == null ? null : (PendingIntent) intent.getParcelableExtra("NOTIFICATION_INTENT"));
        break;
    case STOP:
        stopVpn();
        break;
    }

    return Service.START_STICKY;
}

From source file:riddimon.android.asianetautologin.LoginService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    if (intent != null) {
        String action = intent.getAction();
        Thread thread = new Thread(new ISPTask(this, action), "isp_worker");
        thread.start();/*from  www .ja  va2  s. co m*/
    }
    return Service.START_STICKY;
}

From source file:com.rp.podemu.PodEmuService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    try {//from  w  ww  . ja  v  a  2  s  .c  om
        if (bufferThread != null || bgThread != null) {
            PodEmuLog.debug("Service already running...");
            return Service.START_STICKY;
        }

        reloadBaudRate();

        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notification_icon)
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.podemu_icon))
                .setContentTitle("PodEmu").setContentText("iPod emulation is running")
                .setContentIntent(pendingIntent).build();
        startForeground(1, notification);

        /*
         * Buffer thread is used only to read from serial interface and put bytes into internal buffer.
         * It is important for this thread to have the highest priority, because internal buffer
         * of serial devices usually has only 255 bytes and not reading data fast enough can cause
         * some bytes to be lost.
         */
        if (bufferThread == null) {
            bufferThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        serialInterface = serialInterfaceBuilder.getSerialInterface();
                        int numBytesRead;

                        // some devices have problem reading less then internal chip buffer
                        // size (due to android bug 28023), therefore we need to set
                        // expected buffer size equal to internal buffer size of the device
                        byte buffer[] = new byte[serialInterface.getReadBufferSize()];
                        PodEmuLog.debug("Buffer thread started.");

                        serialInterface.setBaudRate(Integer.parseInt(baudRate));

                        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                        //android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);

                        numBytesRead = 0;
                        while (true) {
                            try {
                                if (numBytesRead < 0 || !serialInterface.isConnected()) {
                                    PodEmuLog.error("Read attempt nr " + failedReadCount
                                            + " when interface is disconnected");
                                    Thread.sleep(100);
                                    failedReadCount++;
                                    if (failedReadCount > 50) // 5 seconds
                                    {
                                        PodEmuLog.error(
                                                "Something wrong happen. Reading from serial interface constantly failing. Terminating service.");
                                        stopSelf();
                                    }
                                }

                                // Reading incoming data
                                while ((numBytesRead = serialInterface.read(buffer)) > 0) {
                                    //PodEmuLog.debug("RECEIVED BYTES: " + numBytesRead);
                                    for (int j = 0; j < numBytesRead; j++) {
                                        inputBuffer.add(buffer[j]);
                                    }
                                }
                                if (numBytesRead == 0) {
                                    Thread.sleep(10);
                                    failedReadCount = 0;
                                }

                            } catch (Exception e) {
                                if (!(e instanceof InterruptedException)) {
                                    // sth wrong happen, just log and throw it up
                                    PodEmuLog.printStackTrace(e);
                                }
                                throw e;
                            }
                        }

                    } catch (InterruptedException e) {
                        PodEmuLog.debug("Buffer thread interrupted!");
                    }
                }
            });
            bufferThread.start();
        }

        /*
         * This is polling thread that will only post message 0x0027 to the serial interface if
         * polling mode is enabled.
         */
        if (pollingThread == null) {
            pollingThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        boolean stopCommandSent = false;
                        MediaPlayback mediaPlayback = MediaPlayback.getInstance();

                        while (true) {

                            if (oapMessenger.getPollingMode()) {
                                if (mediaPlayback.getTrackStatusChanged()) {
                                    mediaPlayback.setTrackStatusChanged(false);
                                    oapMessenger.oap_04_write_polling_track_status_changed(
                                            mediaPlayback.getCurrentPlaylist().getCurrentTrackPos());
                                }

                                if (!mediaPlayback.isPlaying() && !stopCommandSent) {
                                    oapMessenger.oap_04_write_polling_playback_stopped();
                                    stopCommandSent = true;
                                }
                                if (mediaPlayback.isPlaying())
                                    stopCommandSent = false;

                                oapMessenger.oap_04_write_polling_elapsed_time();
                            }
                            Thread.sleep(500);
                        }

                    } catch (InterruptedException e) {
                        PodEmuLog.debug("Polling thread interrupted!");
                    }
                }
            });
            pollingThread.start();
        }

        /*
         * this is main thread that reads data from serial interface internal buffer
         * and processes it byte by byte
         */
        if (bgThread == null) {
            bgThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        int numBytesRead = 0;
                        byte buffer[] = new byte[1];
                        PodEmuLog.debug("Background thread started.");

                        while (true) {
                            //serialInterface.write("Service is running...".getBytes(), 21);

                            numBytesRead = 0;
                            // Reading incoming data
                            while (inputBuffer.remove(buffer) > 0) {
                                oapMessenger.oap_receive_byte(buffer[0]);
                                numBytesRead++;
                            }

                            // sending updates
                            while (podEmuMessageVector.size() > 0) {
                                PodEmuMessage podEmuMessage = podEmuMessageVector.get(0);
                                MediaPlayback.getInstance().updateCurrentlyPlayingTrack(podEmuMessage);
                                podEmuMessageVector.remove(0);
                            }
                            oapMessenger.flush();

                            if (numBytesRead == 0) {
                                Thread.sleep(10);
                            }
                        }
                    } catch (InterruptedException e) {
                        PodEmuLog.debug("Background processing thread interrupted!");
                    } catch (Exception e) {
                        PodEmuLog.printStackTrace(e);
                        throw e;
                    }
                }

            });
            bgThread.start();
        }

        PodEmuLog.debug("Service started");
        return Service.START_STICKY;
    } catch (Exception e) {
        PodEmuLog.printStackTrace(e);
        throw e;
    }
}

From source file:com.ultrafunk.network_info.service.NetworkStateService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if ((intent != null) && (intent.getAction() != null)) {
        final String action = intent.getAction();

        //   Log.e(this.getClass().getSimpleName(), "onStartCommand(): " + action);

        if (Constants.ACTION_UPDATE_SERVICE_STATE.equals(action)) {
            initEnabledWidgets(new EnabledWidgets(
                    intent.getBooleanExtra(Constants.EXTRA_ENABLED_WIDGETS_MOBILE_DATA, false),
                    intent.getBooleanExtra(Constants.EXTRA_ENABLED_WIDGETS_WIFI, false)));
        } else {//from   w w w. j a  v  a2 s  .  c  o m
            final Handler handler = new Handler();

            if (Constants.ACTION_WIFI_CONNECTING.equals(action)) {
                handler.postDelayed(new Runnable() {
                    public void run() {
                        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

                        if ((wifiInfo != null) && (wifiInfo.getSupplicantState() == SupplicantState.SCANNING))
                            localBroadcastManager.sendBroadcastSync(new Intent(Constants.ACTION_WIFI_SCANNING));
                    }
                }, 5 * 1000);
            } else if (Constants.ACTION_WIFI_CONNECTED.equals(action)) {
                handler.postDelayed(new Runnable() {
                    public void run() {
                        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

                        if ((wifiInfo != null) && (wifiInfo.getLinkSpeed() != -1))
                            localBroadcastManager
                                    .sendBroadcastSync(new Intent(Constants.ACTION_WIFI_LINK_SPEED));
                    }
                }, 3 * 1000);
            } else if (Constants.ACTION_DATA_CONNECTED.equals(action)) {
                handler.postDelayed(new Runnable() {
                    public void run() {
                        isWaitingForDataUsage = false;

                        if (telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)
                            localBroadcastManager
                                    .sendBroadcastSync(new Intent(Constants.ACTION_DATA_USAGE_UPDATE));
                    }
                }, 500);
            }
        }
    }

    return Service.START_STICKY;
}

From source file:com.readystatesoftware.android.geras.mqtt.GerasMqttService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String host = intent.getStringExtra(EXTRA_HOST);
    String apiKey = intent.getStringExtra(EXTRA_API_KEY);
    ArrayList<GerasSensorConfig> monitors = intent.getParcelableArrayListExtra(EXTRA_SENSOR_MONITORS);
    for (GerasSensorConfig m : monitors) {
        mSensorMonitorMap.put(m.getSensorType(), m);
    }// w  ww . jav a 2  s  .  com
    mLocationMonitor = intent.getParcelableExtra(EXTRA_LOCATION_MONTITOR);
    mNotificationTarget = (Class) intent.getSerializableExtra(EXTRA_NOTIFICATION_TARGET_CLASS);
    sIsRunning = true;
    showNotification();
    connect(host, apiKey);
    return Service.START_STICKY;
}

From source file:org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.PassiveService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    startThread();
    return Service.START_STICKY;
}