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:com.adam.aslfms.service.ScrobblingService.java

@Override
public int onStartCommand(Intent i, int flags, int startId) {
    handleCommand(i, startId);//w  ww  .j  a v  a 2s .  com
    if (settings.isOnGoingEnabled(Util.checkPower(mCtx))) {
        if (mCurrentTrack != null) {
            String ar = mCurrentTrack.getArtist();
            String tr = mCurrentTrack.getTrack();
            String api = mCurrentTrack.getMusicAPI().readAPIname();

            // Heart intent
            Intent heartIntent = new Intent(mCtx, ScrobblingService.class);
            heartIntent.setAction(ScrobblingService.ACTION_HEART);
            PendingIntent heartPendingIntent = PendingIntent.getService(mCtx, 0, heartIntent, 0);
            NotificationCompat.Action heartAction = new NotificationCompat.Action.Builder(
                    R.mipmap.ic_status_wail_love_track, "", heartPendingIntent).build();

            Intent targetIntent = new Intent(mCtx, SettingsActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(mCtx, 0, targetIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(mCtx).setContentTitle(tr)
                    .setSmallIcon(R.mipmap.ic_notify).setContentText(ar + " :" + api)
                    .setPriority(NotificationCompat.PRIORITY_MIN).addAction(heartAction)
                    .setContentIntent(contentIntent);

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2) {
                builder.setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.mipmap.ic_launcher));
            }

            this.startForeground(14619, builder.build());

            if (!settings.isNotifyEnabled(Util.checkPower(mCtx))) {
                Intent iNoti = new Intent(mCtx, ForegroundHide.class);
                startService(iNoti);
            }
        }
    } else {
        this.stopForeground(true); // TODO: test if this conflicts/stops scrobbles
    }
    return Service.START_STICKY;
}

From source file:com.darshancomputing.BatteryIndicatorPro.BatteryInfoService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO: Do I need a filter, or is it okay to just update(null) every time?
    //if (intent != null && intent.getBooleanExtra(EXTRA_UPDATE_PREDICTOR, false))
    update(null);/* ww  w .j a va 2s . c  o m*/

    return Service.START_STICKY;
}

From source file:org.metawatch.manager.MetaWatchService.java

@Override
public synchronized int onStartCommand(final Intent intent, int flags, int startId) {
    if (Preferences.logging)
        Log.d(MetaWatchStatus.TAG, "MetaWatchService.onStartCommand()");
    if (intent != null) {
        switch (intent.getIntExtra(COMMAND_KEY, -1)) {
        case SILENT_MODE_ENABLE:
            setSilentMode(true);/*from  w  w  w .  j  ava 2s.c o  m*/
            break;
        case SILENT_MODE_DISABLE:
            setSilentMode(false);
            break;
        case INVERT_SILENT_MODE:
            setSilentMode(!silentMode);
            break;
        case SEND_BYTE_ARRAY:
            sendQueue.add(intent.getByteArrayExtra(BYTE_ARRAY));
            break;
        }
    }
    return Service.START_STICKY;
}

From source file:com.google.android.libraries.cast.companionlibrary.notification.VideoCastNotificationService.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);
            onRemoteMediaPlayerStatusUpdated(mCastManager.getPlaybackStatus());
            if (mNotification == null) {
                try {
                    setUpNotification(mCastManager.getRemoteMediaInformation());
                } catch (TransientNetworkDisconnectionException | NoConnectionException e) {
                    LOGE(TAG, "onStartCommand() failed to get media", e);
                }/*from   w w  w .jav  a 2 s  . co m*/
            }
            if (mVisible && mNotification != null) {
                startForeground(NOTIFICATION_ID, mNotification);
            } else {
                stopForeground(true);
            }
        }
    }

    return Service.START_STICKY;
}

From source file:io.scalac.locationprovider.SendMockLocationService.java

@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
    // Get the type of test to run
    mTestRequest = startIntent.getAction();

    /*/*from w w  w  .  j a v a2 s. c  o  m*/
     * If the incoming Intent was a request to run a one-time or continuous test
     */
    if ((TextUtils.equals(mTestRequest, LocationUtils.ACTION_START_ONCE))
            || (TextUtils.equals(mTestRequest, LocationUtils.ACTION_START_CONTINUOUS))) {

        // Get the pause interval and injection interval
        mPauseInterval = startIntent.getIntExtra(LocationUtils.EXTRA_PAUSE_VALUE, 2);
        mInjectionInterval = startIntent.getIntExtra(LocationUtils.EXTRA_SEND_INTERVAL, 1);
        mMockId = startIntent.getStringExtra(LocationUtils.EXTRA_MOCK_ID);

        // Post a notification in the notification bar that a test is starting
        postNotification(getString(R.string.notification_content_test_start));

        // Create a location client
        mLocationClient = new LocationClient(this, this, this);

        // Start connecting to Location Services
        mLocationClient.connect();

    } else if (TextUtils.equals(mTestRequest, LocationUtils.ACTION_STOP_TEST)) {

        // Remove any existing notifications
        removeNotification();

        // Send a message back to the main activity that the test is stopping
        sendBroadcastMessage(LocationUtils.CODE_TEST_STOPPED, 0);

        // Stop this Service
        stopSelf();
    }

    /*
     * Tell the system to keep the Service alive, but to discard the Intent that
     * started the Service
     */
    return Service.START_STICKY;
}

From source file:org.torproject.android.service.TorService.java

public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null)
        new Thread(new IncomingIntentRouter(intent)).start();
    else//from w  w w  .  j a  v a2  s .  co m
        Log.d(TAG, "Got null onStartCommand() intent");

    return Service.START_STICKY;
}

From source file:com.google.fpl.gim.examplegame.MainService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // The service is starting, due to a call to startService()
    Utils.logDebug(TAG, "onStartCommand");
    return Service.START_STICKY;
}

From source file:com.nttec.everychan.ui.tabs.TabsTrackerService.java

@SuppressLint("InlinedApi")
@Override/*from  ww w . j a v a2 s  .c  om*/
public int onStartCommand(Intent intent, int flags, int startId) {
    onStart(intent, startId);
    return Service.START_STICKY;
}

From source file:com.nbplus.push.PushService.java

/**
 * Called by the system every time a client explicitly starts the service by calling
 * {@link android.content.Context#startService}, providing the arguments it supplied and a
 * unique integer token representing the start request.  Do not call this method directly.
 * <p/>//  ww  w  .j av a2s  .com
 * <p>For backwards compatibility, the default implementation calls
 * {@link #onStart} and returns either {@link #START_STICKY}
 * or {@link #START_STICKY_COMPATIBILITY}.
 * <p/>
 * <p>If you need your application to run on platform versions prior to API
 * level 5, you can use the following model to handle the older {@link #onStart}
 * callback in that case.  The <code>handleCommand</code> method is implemented by
 * you as appropriate:
 * <p/>
 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/ForegroundService.java
 * start_compatibility}
 * <p/>
 * <p class="caution">Note that the system calls this on your
 * service's main thread.  A service's main thread is the same
 * thread where UI operations take place for Activities running in the
 * same process.  You should always avoid stalling the main
 * thread's event loop.  When doing long-running operations,
 * network calls, or heavy disk I/O, you should kick off a new
 * thread, or use {@link android.os.AsyncTask}.</p>
 *
 * @param intent  The Intent supplied to {@link android.content.Context#startService},
 *                as given.  This may be null if the service is being restarted after
 *                its process has gone away, and it had previously returned anything
 *                except {@link #START_STICKY_COMPATIBILITY}.
 * @param flags   Additional data about this start request.  Currently either
 *                0, {@link #START_FLAG_REDELIVERY}, or {@link #START_FLAG_RETRY}.
 * @param startId A unique integer representing this specific request to
 *                start.  Use with {@link #stopSelfResult(int)}.
 * @return The return value indicates what semantics the system should
 * use for the service's current started state.  It may be one of the
 * constants associated with the {@link #START_CONTINUATION_MASK} bits.
 * @see #stopSelfResult(int)
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String pushInterfaceServerAddress = null;
    String action = (intent != null) ? intent.getAction() : null;
    Log.d(TAG, "onStartCommand in service.. action = " + action);
    if (action == null) {
        action = PushConstants.ACTION_START_SERVICE;
        pushInterfaceServerAddress = mPrefs.getString(PushConstants.PREF_KEY_PUSH_IF_ADDRESS, "");
    }
    if (action.equals(PushConstants.ACTION_START_SERVICE)) {
        if (intent != null && action != null) {
            pushInterfaceServerAddress = intent.getStringExtra(PushConstants.EXTRA_START_SERVICE_IFADDRESS);
        }
        if (!StringUtils.isEmptyString(pushInterfaceServerAddress)) {
            if (mPushInterfaceServerAddress == null
                    || !pushInterfaceServerAddress.equals(mPushInterfaceServerAddress)) {
                mPushInterfaceServerAddress = pushInterfaceServerAddress;
                mPrefs.edit().putString(PushConstants.PREF_KEY_PUSH_IF_ADDRESS, mPushInterfaceServerAddress)
                        .apply();

                if (mPushRunnable.getState() == PushRunnable.State.IfRetrieving) {
                    if (mIfTask != null) {
                        mIfTask.cancel(true);
                    }
                    mIfTask = null;
                }

                if (mPushRunnable.getState() == PushRunnable.State.Connected) {
                    mPushRunnable.releasePushClientSocket(false);
                }
                Log.d(TAG,
                        "mPushInterfaceServerAddress is (re)setted!!! getPushGatewayInformationFromServer()");
                getPushGatewayInformationFromServer();
            } else {
                if (pushInterfaceServerAddress.equals(mPushInterfaceServerAddress)) {
                    Log.d(TAG, ">> Same address... do not anything...");
                    return Service.START_STICKY;
                }
            }
        } else {
            Log.e(TAG, ">> mPushInterfaceServerAddress is empty... maybe logout???? !!!");
            mPushRunnable.releasePushClientSocket(false);
        }
    } else if (action.equals(PushConstants.ACTION_GET_STATUS)) {
        mPushRunnable.sendSatusChangedBroadcastMessage(PushConstants.PUSH_STATUS_WHAT_NORMAL);
    }

    /**
     * ? ??? .
     */
    return Service.START_STICKY;//super.onStartCommand(intent, flags, startId);
}

From source file:RhodesService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Logger.D(TAG, "onStartCommand");
    try {/*from w w  w .  ja v a 2  s  . c  o m*/
        handleCommand(intent, startId);
    } catch (Exception e) {
        Logger.E(TAG, "Can't handle service command");
        Logger.E(TAG, e);
    }
    return Service.START_STICKY;
}