Example usage for android.app Service START_NOT_STICKY

List of usage examples for android.app Service START_NOT_STICKY

Introduction

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

Prototype

int START_NOT_STICKY

To view the source code for android.app Service START_NOT_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 ), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context#startService Context.startService(Intent) .

Usage

From source file:org.wso2.carbon.iot.android.sense.scheduler.DataUploaderService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    context = this;

    Log.i("SENDING DATA", "service started");

    Runnable runnable = new Runnable() {
        @Override/* w w w  .  j av  a  2 s .c  o  m*/
        public void run() {

            try {

                JSONObject jsonObject = new JSONObject();
                JSONArray sensorJsonArray = new JSONArray();

                jsonObject.put("owner", LocalRegister.getUsername(context));
                jsonObject.put("deviceId", LocalRegister.getDeviceId(context));

                boolean noSensorData = false;
                boolean noBatteryData = false;
                boolean noLocationData = false;

                List<SensorData> sensorDataMap = DataMap.getSensorDataMap();
                if (sensorDataMap.size() <= 0) {
                    noSensorData = true;
                }
                for (SensorData sensorData : sensorDataMap) {
                    JSONObject sensorJsonObject = new JSONObject();
                    sensorJsonObject.put("time", sensorData.getTimestamp());
                    sensorJsonObject.put("key", sensorData.getSensorType());
                    sensorJsonObject.put("value", sensorData.getSensorValues());
                    sensorJsonArray.put(sensorJsonObject);
                }
                DataMap.resetSensorDataMap();

                List<BatteryData> batteryDataMap = DataMap.getBatteryDataMap();
                if (batteryDataMap.size() <= 0) {
                    noBatteryData = true;
                }
                for (BatteryData batteryData : batteryDataMap) {
                    JSONObject batteryJsonObject = new JSONObject();
                    batteryJsonObject.put("time", batteryData.getTimestamp());
                    batteryJsonObject.put("key", "battery");
                    batteryJsonObject.put("value", batteryData.getLevel());
                    sensorJsonArray.put(batteryJsonObject);
                }
                DataMap.resetBatteryDataMap();

                List<LocationData> locationDataMap = DataMap.getLocationDataMap();
                if (locationDataMap.size() <= 0) {
                    noLocationData = true;
                }
                for (LocationData locationData : locationDataMap) {
                    JSONObject locationJsonObject = new JSONObject();
                    locationJsonObject.put("time", locationData.getTimeStamp());
                    locationJsonObject.put("key", "GPS");
                    locationJsonObject.put("value",
                            locationData.getLatitude() + "," + locationData.getLongitude());
                    sensorJsonArray.put(locationJsonObject);
                }
                DataMap.resetLocationDataMap();

                jsonObject.put("values", sensorJsonArray);

                if (!(noSensorData && noBatteryData && noLocationData)) {
                    SenseClient client = new SenseClient(context);
                    client.sendSensorDataToServer(jsonObject.toString());

                }

            } catch (JSONException e) {
                Log.i("Data Upload", " Json Data Parsing Exception");
            }
        }
    };

    Thread dataUploaderThread = new Thread(runnable);
    dataUploaderThread.start();

    return Service.START_NOT_STICKY;
}

From source file:bala.padio.Player.java

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    Runnable runnable = new Runnable() {
        @Override/*  w w  w .  j a  v  a 2s . c  o  m*/
        public void run() {
            try {
                boolean isStop = intent.getBooleanExtra(CmdStop, false);

                if (isStop) {
                    Stop();
                } else {
                    Play(Settings.getSelectedChannelUrl());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    new Thread(runnable).start();

    return Service.START_NOT_STICKY;
}

From source file:org.mythdroid.util.UpdateService.java

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    if (intent != null)
        handleCommand(intent);//from  w  w w.  j  a  v a 2  s . c  om
    return Service.START_NOT_STICKY;
}

From source file:org.telegram.messenger.LocationSharingService.java

public int onStartCommand(Intent intent, int flags, int startId) {
    if (getInfos().isEmpty()) {
        stopSelf();/* w w w  .  ja  va 2 s  .c  om*/
    }
    if (builder == null) {
        Intent intent2 = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent2.setAction("org.tmessages.openlocations");
        intent2.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0,
                intent2, 0);

        builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext);
        builder.setWhen(System.currentTimeMillis());
        builder.setSmallIcon(R.drawable.live_loc);
        builder.setContentIntent(contentIntent);
        NotificationsController.checkOtherNotificationsChannel();
        builder.setChannelId(NotificationsController.OTHER_NOTIFICATIONS_CHANNEL);
        builder.setContentTitle(LocaleController.getString("AppName", R.string.AppName));
        Intent stopIntent = new Intent(ApplicationLoader.applicationContext, StopLiveLocationReceiver.class);
        builder.addAction(0, LocaleController.getString("StopLiveLocation", R.string.StopLiveLocation),
                PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, stopIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT));
    }

    updateNotification(false);
    startForeground(6, builder.build());
    return Service.START_NOT_STICKY;
}

From source file:net.dian1.player.service.PlayerService.java

@Override
public int onStartCommand(Intent intent, int flag, int startId) {
    super.onStartCommand(intent, flag, startId);
    if (intent == null) {
        return Service.START_NOT_STICKY;
    }/*from  w ww.  j ava 2  s.co m*/

    String action = intent.getAction();
    Log.i(Dian1Application.TAG, "Player Service onStart - " + action);

    if (action.equals(ACTION_STOP)) {
        stopSelfResult(startId);
        return Service.START_NOT_STICKY;
    }

    if (action.equals(ACTION_BIND_LISTENER)) {
        mRemoteEngineListeners = Dian1Application.getInstance().fetchPlayerEngineListener();
        return Service.START_NOT_STICKY;
    }

    // we need to have up-to-date playlist if any of play,next,prev buttons is pressed
    updatePlaylist();

    if (action.equals(ACTION_PLAY)) {
        mPlayerEngine.play();
        return Service.START_NOT_STICKY;
    }

    if (action.equals(ACTION_NEXT)) {
        mPlayerEngine.next();
        return Service.START_NOT_STICKY;
    }

    if (action.equals(ACTION_PREV)) {
        mPlayerEngine.prev();
        return Service.START_NOT_STICKY;
    }
    return Service.START_NOT_STICKY;
}

From source file:com.tinfoil.sms.utility.MessageService.java

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

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    /*/*ww w  .j a v a2s.c  om*/
     * Creates a notification if there is one to be created and if the user set the preferences
     * to allow notifications
     */
    if (contentTitle != null && contentText != null
            && sharedPrefs.getBoolean(QuickPrefsActivity.NOTIFICATION_BAR_SETTING_KEY, true)) {
        Intent notifyIntent = null;
        PendingIntent in = null;

        final String address = contentTitle.toString();

        if (dba.getUnreadMessageCount() > 1) {

            MessageService.mNotificationManager.cancel(SINGLE);
            //Might need to change this.
            contentTitle = dba.getRow(address).getName();

            contentTitle = this.getString(R.string.new_message_notification_title);
            contentText = dba.getUnreadMessageCount() + " " + this.getString(R.string.unread_email_message);

            // Extra is added so the user will be brought to the main menu
            notifyIntent = new Intent(this.getApplicationContext(), ConversationView.class);
            //notifyIntent.putExtra(multipleNotificationIntent, true);
            notifyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

            in = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(in).setContentTitle(contentTitle).setContentText(contentText)
                    .setTicker(contentTitle + ": " + contentText).setSmallIcon(R.drawable.tinfoil_logo);

            mNotificationManager.notify(MULTI, builder.build());
        } else {
            contentTitle = dba.getRow(address).getName();

            notifyIntent = new Intent(this.getApplicationContext(), SendMessageActivity.class);
            notifyIntent.putExtra(ConversationView.MESSAGE_INTENT, ConversationView.MESSAGE_VIEW);
            notifyIntent.putExtra(notificationIntent, address);
            notifyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

            // Adds the back stack
            stackBuilder.addParentStack(SendMessageActivity.class);

            notifyIntent.putExtra(multipleNotificationIntent, false);

            // Adds the Intent to the top of the stack
            stackBuilder.addNextIntent(notifyIntent);

            in = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

            builder.setContentIntent(in).setContentTitle(contentTitle).setContentText(contentText)
                    .setTicker(contentTitle + ": " + contentText).setSmallIcon(R.drawable.tinfoil_logo);

            mNotificationManager.notify(SINGLE, builder.build());
        }
    }

    if (sharedPrefs.getBoolean(QuickPrefsActivity.NOTIFICATION_BAR_SETTING_KEY, true)) {
        ArrayList<Entry> keyMessage = dba.getAllKeyExchangeMessages();
        if (keyMessage != null && keyMessage.size() > 0) {
            Intent notifyIntent = null;
            PendingIntent in = null;

            notifyIntent = new Intent(this.getApplicationContext(), KeyExchangeManager.class);
            notifyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

            // Adds the back stack
            stackBuilder.addParentStack(KeyExchangeManager.class);

            // Adds the Intent to the top of the stack
            stackBuilder.addNextIntent(notifyIntent);

            in = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

            builder.setContentIntent(in)
                    .setContentTitle(this.getString(R.string.pending_key_exchange_notification))
                    .setContentText(this.getString(R.string.pending_key_exchange_message))
                    .setTicker(this.getString(R.string.pending_key_exchange_notification))
                    .setSmallIcon(R.drawable.key_exchange);

            mNotificationManager.notify(KEY, builder.build());
        } else {
            MessageService.mNotificationManager.cancel(MessageService.KEY);
        }
    }

    this.stopSelf();
    return Service.START_NOT_STICKY;
}

From source file:org.wso2.carbon.iot.android.sense.data.publisher.DataPublisherService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    context = this;
    Log.d(TAG, "service started");
    Runnable runnable = new Runnable() {
        @Override/*w  ww  .j a  v  a2 s  .c o m*/
        public void run() {
            try {

                JSONArray sensorJsonArray = new JSONArray();

                //retreive sensor data.
                List<SensorData> sensorDataMap = SenseDataHolder.getSensorDataHolder();
                for (SensorData sensorData : sensorDataMap) {
                    JSONObject sensorJsonObject = new JSONObject();
                    sensorJsonObject.put(TIME_TAG, sensorData.getTimestamp());
                    sensorJsonObject.put(KEY_TAG, sensorData.getSensorType());
                    sensorJsonObject.put(VALUE_TAG, sensorData.getSensorValues());
                    sensorJsonArray.put(sensorJsonObject);
                }
                SenseDataHolder.resetSensorDataHolder();

                //retreive batter data.
                List<BatteryData> batteryDataMap = SenseDataHolder.getBatteryDataHolder();
                for (BatteryData batteryData : batteryDataMap) {
                    JSONObject batteryJsonObject = new JSONObject();
                    batteryJsonObject.put(TIME_TAG, batteryData.getTimestamp());
                    batteryJsonObject.put(KEY_TAG, "battery");
                    batteryJsonObject.put(VALUE_TAG, batteryData.getLevel());
                    sensorJsonArray.put(batteryJsonObject);
                }
                SenseDataHolder.resetBatteryDataHolder();
                //retreive location data.
                List<LocationData> locationDataMap = SenseDataHolder.getLocationDataHolder();
                for (LocationData locationData : locationDataMap) {
                    JSONObject locationJsonObject = new JSONObject();
                    locationJsonObject.put(TIME_TAG, locationData.getTimeStamp());
                    locationJsonObject.put(KEY_TAG, "GPS");
                    locationJsonObject.put(VALUE_TAG,
                            locationData.getLatitude() + "," + locationData.getLongitude());
                    sensorJsonArray.put(locationJsonObject);
                }
                SenseDataHolder.resetLocationDataHolder();

                //retreive words
                ProcessWords.cleanAndPushToWordMap();
                List<WordData> wordDatMap = SenseDataHolder.getWordDataHolder();
                for (WordData wordData : wordDatMap) {
                    if (wordData.getOccurences() == 0) {
                        continue;
                    }
                    JSONObject wordJsonObject = new JSONObject();
                    wordJsonObject.put(TIME_TAG, System.currentTimeMillis());
                    wordJsonObject.put(KEY_TAG, "word");
                    String word = wordData.getWord();
                    String status = word;
                    if ((!word.equals(SenseConstants.EVENT_LISTENER_STARTED))
                            && (!word.equals(SenseConstants.EVENT_LISTENER_FINISHED))) {
                        status = SenseConstants.EVENT_LISTENER_ONGOING;
                    }
                    String wordValue = wordData.getSessionId() + "," + word + "," + wordData.getOccurences()
                            + "," + status + "," + wordData.getTimestamps();
                    wordJsonObject.put(VALUE_TAG, wordValue);
                    sensorJsonArray.put(wordJsonObject);
                }
                SenseDataHolder.resetWordDataHolder();

                //publish the data
                if (sensorJsonArray.length() > 0) {
                    JSONObject jsonMsgObject = new JSONObject();
                    String user = LocalRegistry.getUsername(context);
                    String deviceId = LocalRegistry.getDeviceId(context);
                    jsonMsgObject.put("owner", user);
                    jsonMsgObject.put("deviceId", deviceId);
                    jsonMsgObject.put("values", sensorJsonArray);
                    MQTTTransportHandler mqttTransportHandler = AndroidSenseMQTTHandler.getInstance(context);
                    if (!mqttTransportHandler.isConnected()) {
                        mqttTransportHandler.connect();
                    }
                    mqttTransportHandler.publishDeviceData(user, deviceId, jsonMsgObject.toString());
                }
            } catch (JSONException e) {
                Log.e(TAG, "Json Data Parsing Exception", e);
            } catch (TransportHandlerException e) {
                Log.e(TAG, "Data Publish Failed", e);
            }
        }
    };
    Thread dataUploaderThread = new Thread(runnable);
    dataUploaderThread.start();
    return Service.START_NOT_STICKY;
}

From source file:name.vdg.respi55.RespiStateManager.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Command cmd = (Command) intent.getSerializableExtra(EXTRA_CMD_ID);
    switch (cmd) {
    case Start:/*  w  ww .  ja  v a  2  s.  c  om*/
        Log.d(TAG, "service started with start intent");
        start();
        break;
    case Stop:
        Log.d(TAG, "service started with stop intent");
        stop();
        break;
    default:
        Log.d(TAG, "service started with unkown intent command");
        break;
    }
    return Service.START_NOT_STICKY;
}

From source file:com.jtxdriggers.android.ventriloid.VentriloidService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    int id = intent.getExtras().getInt("id");
    ServerAdapter db = new ServerAdapter(this);
    server = db.getServer(id);//from w  w w  .  j  a va  2 s  .  com

    items = new ItemData(this);
    queue.clear();

    volumePrefs = getSharedPreferences("VOLUMES" + server.getId(), Context.MODE_PRIVATE);
    passwordPrefs = getSharedPreferences("PASSWORDS" + server.getId(), Context.MODE_PRIVATE);

    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VentriloidWakeLock");
    wakeLock.acquire();

    wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL,
            "VentriloidWifiLock");
    wifiLock.acquire();

    disconnect = true;

    r = new Runnable() {
        public void run() {
            timeout = true;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (timeout) {
                        VentriloInterface.logout();
                        sendBroadcast(new Intent(Main.SERVICE_RECEIVER).putExtra("type",
                                (short) VentriloEvents.V3_EVENT_LOGIN_FAIL));
                        Toast.makeText(getApplicationContext(), "Connection timed out.", Toast.LENGTH_SHORT)
                                .show();
                        reconnectTimer = 10;
                        handler.post(r);
                    }
                }
            }, 9500);
            if (VentriloInterface.login(server.getHostname() + ":" + server.getPort(), server.getUsername(),
                    server.getPassword(), server.getPhonetic())) {
                new Thread(new Runnable() {
                    public void run() {
                        while (VentriloInterface.recv())
                            ;
                    }
                }).start();
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        VentriloEventData data = new VentriloEventData();
                        VentriloInterface.error(data);
                        sendBroadcast(new Intent(Main.SERVICE_RECEIVER).putExtra("type",
                                (short) VentriloEvents.V3_EVENT_LOGIN_FAIL));
                        Toast.makeText(getApplicationContext(), bytesToString(data.error.message),
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
            timeout = false;
        }
    };
    handler.post(r);

    return Service.START_NOT_STICKY;
}

From source file:org.dmfs.tasks.notification.NotificationUpdaterService.java

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

    String intentAction = intent.getAction();
    if (intentAction != null) {
        switch (intentAction) {
        case ACTION_PIN_TASK:
            // nothing special to do right now
            break;

        case ACTION_PINNED_TASK_START:
            updateNotifications(true, true, true);
            delayedCancelHeadsUpNotification();
            break;

        case ACTION_PINNED_TASK_DUE:
            updateNotifications(true, true, true);
            delayedCancelHeadsUpNotification();
            break;

        case ACTION_COMPLETE:
            if (intent.hasExtra(NotificationActionUtils.EXTRA_NOTIFICATION_ACTION)) {
                resolveUndoAction(intent);
                break;
            }/*from   w  w  w .j a  va  2  s .co  m*/
            resolveCompleteAction(intent);
            break;

        case ACTION_UNPIN:
            resolveUnpinAction(intent);
            break;

        case ACTION_DELAY_1D:
        case ACTION_DELAY_1H:
            resolveDelayAction(intent);
            break;

        case NotificationActionUtils.ACTION_UNDO:
        case NotificationActionUtils.ACTION_DESTRUCT:
        case NotificationActionUtils.ACTION_UNDO_TIMEOUT:
            resolveUndoAction(intent);
            break;

        case Intent.ACTION_BOOT_COMPLETED:
        case Intent.ACTION_REBOOT:
        case TaskNotificationHandler.ACTION_FASTBOOT:
            updateNotifications(true, false, false);
            break;

        case Intent.ACTION_DATE_CHANGED:
        case Intent.ACTION_TIME_CHANGED:
        case Intent.ACTION_TIMEZONE_CHANGED:
        case ACTION_NEXT_DAY:
            updateNextDayAlarm();
            updateNotifications(false, false, false);
            break;

        case ACTION_CANCEL_HEADUP_NOTIFICATION:
            updateNotifications(false, false, false);
            break;

        default:
            updateNotifications(false, false, false);
            break;
        }
    }

    // check if the service needs to kept alive
    if (mTasksToPin == null || mTasksToPin.isEmpty()) {
        this.stopSelf();
    }
    return Service.START_NOT_STICKY;

}