Example usage for android.app Activity startService

List of usage examples for android.app Activity startService

Introduction

In this page you can find the example usage for android.app Activity startService.

Prototype

@Override
    public ComponentName startService(Intent service) 

Source Link

Usage

From source file:de.appplant.cordova.plugin.background.BackgroundMode.java

/**
 * Bind the activity to a background service and put them into foreground
 * state.//  ww w .  j a v a 2s  .  co m
 */
private void startService() {
    Activity context = cordova.getActivity();

    Intent intent = new Intent(context, ForegroundService.class);

    if (isDisabled || isBind)
        return;

    try {
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE);

        fireEvent(Event.ACTIVATE, null);

        context.startService(intent);
    } catch (Exception e) {
        fireEvent(Event.FAILURE, e.getMessage());
    }

    isBind = true;
}

From source file:com.SmartDial.BackgroundMode.java

/**
 * Bind the activity to a background service and put them into foreground
 * state./*  w  ww  .ja  v  a  2  s.c  o m*/
 */
private void startService() {
    Log.w("BackgroundMode", "startService");
    Activity context = this.cordova.getActivity();

    Intent intent = new Intent(context, ForegroundService.class);

    if (isDisabled || isBind)
        return;

    try {
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE);

        fireEvent(Event.ACTIVATE, null);

        context.startService(intent);
    } catch (Exception e) {
        fireEvent(Event.FAILURE, e.getMessage());
    }

    isBind = true;
}

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

public void startService(Activity activity) {
    if (!isServiceRunning()) {
        Intent intent = new Intent(activity, GerasMqttService.class);
        intent.putExtra(GerasMqttService.EXTRA_HOST, host);
        intent.putExtra(GerasMqttService.EXTRA_API_KEY, apiKey);
        intent.putExtra(GerasMqttService.EXTRA_SENSOR_MONITORS, mSensorMonitors);
        intent.putExtra(GerasMqttService.EXTRA_LOCATION_MONTITOR, mLocationMonitor);
        intent.putExtra(GerasMqttService.EXTRA_NOTIFICATION_TARGET_CLASS, activity.getClass());
        activity.startService(intent);
    }/*w  w  w  .java 2 s  .  co m*/
}

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

@Override
public void onStart() {
    Activity activity = this.cordova.getActivity();
    SharedPreferences sharedPref = activity.getSharedPreferences(USER_DATA_PREF, Context.MODE_PRIVATE);
    Boolean pActive = this.getPedometerIsActive(sharedPref);
    if (pActive) {
        if (stepCounterIntent == null) {
            stepCounterIntent = new Intent(activity, StepCounterService.class);
            activity.startService(stepCounterIntent);
        }/*from www .  j  a va2  s  .  com*/

        if (!bound) {
            activity.bindService(stepCounterIntent, mConnection, Context.BIND_AUTO_CREATE);
        }

    }

    super.onStart();
}

From source file:com.tenforwardconsulting.cordova.bgloc.BackgroundGeolocationPlugin.java

public ComponentName startBackgroundService() {
    if (isEnabled) {
        return null;
    }/*from w  ww  .  ja  va2s. c  om*/

    Activity activity = this.cordova.getActivity();
    Log.d(TAG, "Starting bg service");

    locationServiceIntent = new Intent(activity, LocationService.class);
    locationServiceIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);
    // locationServiceIntent.putExtra("config", config.toParcel().marshall());
    locationServiceIntent.putExtra("config", config);
    isEnabled = true;

    return activity.startService(locationServiceIntent);
}

From source file:org.jared.synodroid.ds.action.DownloadOriginalLinkAction.java

public void execute(ResponseHandler handlerP, SynoServer serverP) throws Exception {
    /*StringBuffer data = serverP.getDSMHandlerFactory().getDSHandler().getOriginalFile(task);
    OriginalFile ori = new OriginalFile();
    String[] temp = task.originalLink.split("/");
    ori.fileName = temp[(temp.length) - 1];
    ori.rawData = data;//from w w  w  . ja  va  2  s.  c  o  m
    serverP.fireMessage(handlerP, ResponseHandler.MSG_ORIGINAL_FILE_RETRIEVED, ori);
    */
    Activity a = ((Fragment) handlerP).getActivity();
    Intent msgIntent = new Intent(a, DownloadOriginalIntentService.class);
    msgIntent.putExtra(DownloadOriginalIntentService.TASKID, task.taskId);
    msgIntent.putExtra(DownloadOriginalIntentService.ORIGINAL_LINK, task.originalLink);
    msgIntent.putExtra(DownloadOriginalIntentService.COOKIES, serverP.getCookies());
    msgIntent.putExtra(DownloadOriginalIntentService.DSM_VERSION, serverP.getDsmVersion().getTitle());
    msgIntent.putExtra(DownloadOriginalIntentService.PATH, serverP.getUrl());
    msgIntent.putExtra(DownloadOriginalIntentService.DEBUG, ((Synodroid) a.getApplication()).DEBUG);
    a.startService(msgIntent);
}

From source file:com.tenforwardconsulting.cordova.BackgroundGeolocationPlugin.java

protected void startBackgroundService() {
    if (!isServiceRunning) {
        log.info("Starting bg service");
        Activity activity = getActivity();
        Intent locationServiceIntent = new Intent(activity, LocationService.class);
        locationServiceIntent.putExtra("config", config);
        locationServiceIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);
        // start service to keep service running even if no clients are bound to it
        activity.startService(locationServiceIntent);
        isServiceRunning = true;/*from w w w .  j  a  v a2 s  . com*/
    }
}

From source file:com.zion.htf.ui.fragment.ArtistSoundcloudFragment.java

/**
 * Starts the service and request the activity to bind to it
 * @param activity the fragment's activity
 * @param tracks the list of {@link com.zion.htf.data.SoundcloudTrack}s to pass to the service
 *///from  w ww  .ja  v a 2 s .  c  om
private void startService(Activity activity, ArrayList<SoundcloudTrack> tracks) {
    // Start the service, passing it the playlist
    Intent intent = new Intent(activity, MediaPlayerService.class);
    intent.putExtra(MediaPlayerService.EXTRA_TRACKS, tracks);
    intent.setAction(MediaPlayerService.ACTION_QUEUE_TRACKS);
    intent.putExtra(MediaPlayerService.EXTRA_ARTIST_ID, this.artist.getId());
    intent.putExtra(MediaPlayerService.EXTRA_ARTIST_PHOTO, this.artist.getPictureResourceId());
    activity.startService(intent);
}

From source file:com.gbaldera.tipaypal.TipaypalModule.java

@Kroll.method
public void initialize(HashMap params) {
    KrollDict dict = new KrollDict(params);

    client_id = TiConvert.toString(dict, PARAM_CLIENT_ID);
    receiver_email = TiConvert.toString(dict, PARAM_RECEIVER_EMAIL);
    environment = TiConvert.toString(dict, PARAM_ENVIRONMENT);
    skip_credit_card = TiConvert.toBoolean(dict, PARAM_SKIP_CREDIT_CARD, false);

    if (environment == null) {
        environment = ENVIRONMENT_NO_NETWORK;
    }/*from   w ww .j a va 2s . c  om*/

    if (client_id == null || receiver_email == null) {
        Log.w(TAG, "The CLIENT ID and RECEIVER EMAIL params are required");
        return;
    }

    Log.d(TAG, PARAM_ENVIRONMENT + ": " + environment);

    Activity currentActivity = TiApplication.getAppCurrentActivity();
    Intent intent = new Intent(currentActivity, PayPalService.class);

    if (isPayPalServiceRunning()) // if the service is already running stop it first
    {
        currentActivity.stopService(intent);
    }

    // set to PaymentActivity.ENVIRONMENT_PRODUCTION to move real money.
    // set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials from https://developer.paypal.com
    // set to PaymentActivity.ENVIRONMENT_NO_NETWORK to kick the tires without communicating to PayPal's servers.
    intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, environment);

    intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, receiver_email);
    intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, client_id);

    currentActivity.startService(intent);
}

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

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
    LOG.i(TAG, "execute()");
    Boolean result = true;/*from  w  w  w.j  a va  2 s  .  c o m*/

    Activity activity = this.cordova.getActivity();
    stepCounterIntent = new Intent(activity, StepCounterService.class);

    //Get stored value for pedometerActive
    SharedPreferences sharedPref = activity.getSharedPreferences(USER_DATA_PREF, Context.MODE_PRIVATE);
    Boolean pActive = this.getPedometerIsActive(sharedPref);

    if (ACTION_CAN_COUNT_STEPS.equals(action)) {
        Boolean can = deviceHasStepCounter(activity.getPackageManager());
        Log.i(TAG, "Checking if device has step counter APIS: " + can);
        callbackContext.success(can ? 1 : 0);
    } else if (ACTION_START.equals(action)) {

        if (!pActive) {
            Log.i(TAG, "Starting StepCounterService");
            //Update pedometerActive preference
            this.setPedometerIsActive(sharedPref, true);
            activity.startService(stepCounterIntent);
        } else {
            Log.i(TAG, "StepCounterService Already Started before, just binding to it");
        }

        if (!bound) {
            Log.i(TAG, "Binding StepCounterService");
            activity.bindService(stepCounterIntent, mConnection, Context.BIND_AUTO_CREATE);
        } else {
            Log.i(TAG, "StepCounterService already binded");
        }

        //Try getting given param (starting value)
        Integer startingValue = 0;
        try {
            if (data.length() > 0) {
                startingValue = data.getInt(0);
            }
        } catch (JSONException error) {
            Log.i(TAG, "JSON EXCEPTION While Reading startingValue from 'execute' parameters (JSONArray)");
        }

        //Reset TOTAL COUNT on start
        CordovaStepCounter.setTotalCount(sharedPref, startingValue);
        callbackContext.success(startingValue);
    } else if (ACTION_STOP.equals(action)) {
        if (pActive) {
            Log.i(TAG, "Stopping StepCounterService");
            this.setPedometerIsActive(sharedPref, false);
            activity.stopService(stepCounterIntent);
        } else {
            Log.i(TAG, "StepCounterService already stopped");
        }

        if (bound) {
            Log.i(TAG, "Unbinding StepCounterService");
            activity.unbindService(mConnection);
        } else {
            Log.i(TAG, "StepCounterService already unbinded");
        }

        activity.stopService(stepCounterIntent);
        Integer currentCount = CordovaStepCounter.getTotalCount(sharedPref);
        //Callback with final count
        callbackContext.success(currentCount);
    } else if (ACTION_GET_STEPS.equals(action)) {
        if (!pActive) {
            Log.i(TAG, "Be Careful you're getting a Step count with inactive Pedometer");
        }

        Integer steps = CordovaStepCounter.getTotalCount(sharedPref);
        Log.i(TAG, "Geting steps counted from stepCounterService: " + steps);
        callbackContext.success(steps);
    } else if (ACTION_GET_TODAY_STEPS.equals(action)) {
        if (sharedPref.contains(PEDOMETER_HISTORY_PREF)) {
            String pDataString = sharedPref.getString(PEDOMETER_HISTORY_PREF, "{}");

            Date currentDate = new Date();
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
            String currentDateString = dateFormatter.format(currentDate);

            JSONObject pData = new JSONObject();
            JSONObject dayData = new JSONObject();
            Integer daySteps = -1;
            try {
                pData = new JSONObject(pDataString);
                Log.d(TAG, " got json shared prefs " + pData.toString());
            } catch (JSONException err) {
                Log.d(TAG, " Exception while parsing json string : " + pDataString);
            }

            if (pData.has(currentDateString)) {
                try {
                    dayData = pData.getJSONObject(currentDateString);
                    daySteps = dayData.getInt("steps");
                } catch (JSONException err) {
                    Log.e(TAG, "Exception while getting Object from JSON for " + currentDateString);
                }
            }

            Log.i(TAG, "Getting steps for today: " + daySteps);
            callbackContext.success(daySteps);
        } else {
            Log.i(TAG, "No steps history found in stepCounterService !");
            callbackContext.success(-1);
        }
    } else if (ACTION_GET_HISTORY.equals(action)) {
        if (sharedPref.contains(PEDOMETER_HISTORY_PREF)) {
            String pDataString = sharedPref.getString(PEDOMETER_HISTORY_PREF, "{}");
            Log.i(TAG, "Getting steps history from stepCounterService: " + pDataString);
            callbackContext.success(pDataString);
        } else {
            Log.i(TAG, "No steps history found in stepCounterService !");
            callbackContext.success("{}");
        }
    } else {
        Log.e(TAG, "Invalid action called on class " + TAG + ", " + action);
        callbackContext.error("Invalid action called on class " + TAG + ", " + action);
    }

    return result;
}