Example usage for android.content Context startService

List of usage examples for android.content Context startService

Introduction

In this page you can find the example usage for android.content Context startService.

Prototype

@Nullable
public abstract ComponentName startService(Intent service);

Source Link

Document

Request that a given application service be started.

Usage

From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java

private void c2dmRegister(Context context, String senderId) {
    Log.d(TAG, "c2dmRegister: context=" + context + ", senderId=" + senderId);

    Intent intent = new Intent(REQUEST_REGISTRATION_INTENT);
    intent.setPackage(GSF_PACKAGE);/* w  ww.ja  v  a 2 s .co  m*/
    intent.putExtra(EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0));
    intent.putExtra(EXTRA_SENDER, senderId);
    ComponentName name = context.startService(intent);
    if (name == null) {
        // Service not found.
        setStateAndNotify(REGISTRATION_STATE_ERROR, REGISTRATION_SUBSTATE_ERROR_C2DM_NOT_FOUND);
    }
}

From source file:fr.inria.ucn.Helpers.java

/**
 * Collectors and Listeners should use this method to send the results to the service.
 * @param c//  w ww  .j a v a 2s . c  o m
 * @param cid data collection id (maps to mongodb collection used to store the data)
 * @param ts  periodic collection timestamp or event time if triggered by timestamp
 * @param data 
 */
@SuppressLint("SimpleDateFormat")
public static void sendResultObj(Context c, String cid, long ts, JSONObject data) {
    try {

        // wrap the collected data object to a common object format
        JSONObject res = new JSONObject();

        // data collection in the backend db
        res.put("collection", cid);

        // store unique user id to each result object
        res.put("uid", getDeviceUuid(c));

        // app version to help to detect data format changes
        try {
            PackageManager manager = c.getPackageManager();
            PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
            res.put("app_version_name", info.versionName);
            res.put("app_version_code", info.versionCode);
        } catch (NameNotFoundException e) {
        }

        // event and current time in UTC JSON date format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        res.put("ts_event", sdf.format(new Date(ts)));
        res.put("ts", sdf.format(new Date()));
        res.put("tz", TimeZone.getDefault().getID()); // devices current timezone
        res.put("tz_offset", TimeZone.getDefault().getOffset(ts)); // ts offset to this event

        // the data obj
        res.put("data", data);

        // ask the service to handle the data
        Intent intent = new Intent(c, CollectorService.class);
        intent.setAction(Constants.ACTION_DATA);
        intent.putExtra(Constants.INTENT_EXTRA_DATA, res.toString());
        c.startService(intent);

        Log.d(Constants.LOGTAG, res.toString(4));

    } catch (JSONException ex) {
        Log.w(Constants.LOGTAG, "failed to create json obj", ex);
    }
}

From source file:com.juick.android.MainActivity.java

public static void toggleJAMessaging(Context ctx, boolean useJAM) {
    if (isJAMServiceRunning(ctx) && useJAM) {
        return; // already
    }//w  ww  .ja va 2s.c o  m
    XMPPService.log("MainActivity.toggleJAMessaging(" + useJAM + ")");
    if (useJAM) {
        JuickAdvancedApplication.showXMPPToast("toggleJAMessaging: " + useJAM);
        ctx.startService(new Intent(ctx, JAMService.class));
    } else {
        if (isJAMServiceRunning(ctx)) {
            JuickAdvancedApplication.showXMPPToast("toggleJAMessaging: " + useJAM);
            Intent service = new Intent(ctx, JAMService.class);
            service.putExtra("terminate", true);
            ctx.startService(service);
        }
    }
}

From source file:org.altbeacon.beacon.service.Callback.java

/**
 * Tries making the callback, first via messenger, then via intent
 *
 * @param context/* w w  w.j a  va 2 s  .  c om*/
 * @param dataName
 * @param data
 * @return false if it callback cannot be made
 */
public boolean call(Context context, String dataName, Bundle data) {
    boolean useLocalBroadcast = BeaconManager.getInstanceForApplication(context).getScheduledScanJobsEnabled();
    boolean success = false;

    if (useLocalBroadcast) {
        String action = null;
        if (dataName == "rangingData") {
            action = BeaconLocalBroadcastProcessor.RANGE_NOTIFICATION;
        } else {
            action = BeaconLocalBroadcastProcessor.MONITOR_NOTIFICATION;
        }
        Intent intent = new Intent(action);
        intent.putExtra(dataName, data);
        LogManager.d(TAG, "attempting callback via local broadcast intent: %s", action);
        success = LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    } else {
        Intent intent = new Intent();
        intent.setComponent(
                new ComponentName(context.getPackageName(), "org.altbeacon.beacon.BeaconIntentProcessor"));
        intent.putExtra(dataName, data);
        LogManager.d(TAG, "attempting callback via global broadcast intent: %s", intent.getComponent());
        try {
            context.startService(intent);
            success = true;
        } catch (Exception e) {
            LogManager.e(TAG, "Failed attempting to start service: " + intent.getComponent().flattenToString(),
                    e);
        }
    }
    return success;
}

From source file:com.owncloud.android.files.services.TransferRequester.java

/**
 * Call to update multiple files already uploaded
 *//*from  w  w w . j a  v  a 2s.  co  m*/
private void uploadsUpdate(Context context, Account account, OCFile[] existingFiles, Integer behaviour,
        Boolean forceOverwrite, boolean requestedFromAvOfflineJobService) {
    Intent intent = new Intent(context, FileUploader.class);

    intent.putExtra(FileUploader.KEY_ACCOUNT, account);
    intent.putExtra(FileUploader.KEY_FILE, existingFiles);
    intent.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, behaviour);
    intent.putExtra(FileUploader.KEY_FORCE_OVERWRITE, forceOverwrite);

    // Since in Android O and above the apps in background are not allowed to start background
    // services and available offline feature may try to do it, this is the way to proceed
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && requestedFromAvOfflineJobService) {
        intent.putExtra(FileUploader.KEY_IS_AVAILABLE_OFFLINE_FILE, true);
        context.startForegroundService(intent);
    } else {
        context.startService(intent);
    }
}

From source file:com.android.launcher3.widget.DigitalAppWidgetProvider.java

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    /*Intent mIntent = new Intent();
    mIntent.setAction("android.intent.action.battery");
    Intent eintent = new Intent(getExplicitIntent(context, mIntent));
      context.startService(eintent);*/
    Intent mIntent = new Intent(context, BatteryService.class);
    //context.startServiceAsUser(mIntent, UserHandle.CURRENT);
    Log.e("sai", "onUpdate startService");
    context.startService(mIntent);
    for (int appWidgetId : appWidgetIds) {
        float ratio = WidgetUtils.getScaleRatio(context, null, appWidgetId);
        updateClock(context, appWidgetManager, appWidgetId, ratio);
    }/*ww  w  .  j  av  a 2s .c  o  m*/
    startAlarmOnQuarterHour(context);
    // cg sai.pan begin
    Log.e("sai", "mLocationClient start");
    if (mLocationClient == null) {
        Log.e("sai", "onUpdate mLocationClient == null");
    } else {
        Log.e("sai", "onUpdate mLocationClient != null");
    }
    //mLocationClient.start();//?SDK start????isstartrequest
    //mLocationClient.requestLocation();
    //requestLocation(context);
    // cg sai.pan end
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

From source file:com.juick.android.MainActivity.java

public static boolean commandJAMService(Context ctx, String command) {
    if (isJAMServiceRunning(ctx)) {
        Intent service = new Intent(ctx, JAMService.class);
        String[] split = command.split(":");
        if (split.length == 1) {
            service.putExtra(command, true);
        } else {/*from w  ww. ja  v  a 2  s  . c o  m*/
            service.putExtra(split[0], split[1]);
        }
        ctx.startService(service);
        return true;
    } else {
        return false;
    }
}

From source file:com.ultrafunk.network_info.receiver.WifiStatusReceiver.java

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

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

    updateWifiViews = true;/*w  ww .  j ava  2 s .c  o  m*/

    wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    wifiState = wifiManager.getWifiState();
    wifiInfo = wifiManager.getConnectionInfo();

    if ((wifiState == WifiManager.WIFI_STATE_ENABLED) && (wifiInfo.getIpAddress() == 0))
        detailedState = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());

    if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
        if (isConnectionReady(intent)) {
            String securityString = WifiUtils.getSecurityString(context, wifiManager, wifiInfo.getBSSID());
            NetworkStateService.setWifiSecurityString(securityString);
            detailsString = context.getString(R.string.security) + ": " + securityString;

            Intent serviceIntent = new Intent(context, NetworkStateService.class);
            serviceIntent.setAction(Constants.ACTION_WIFI_CONNECTED);
            context.startService(serviceIntent);
        }

        partiallyUpdateWidgets(context);
    } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)
            || Constants.ACTION_WIFI_SCANNING.equals(action)) {
        partiallyUpdateWidgets(context);
    } else if (Intent.ACTION_SCREEN_ON.equals(action) || Constants.ACTION_WIFI_LINK_SPEED.equals(action)) {
        if (isConnected()) {
            setDetailsString(context);
            partiallyUpdateWidgets(context);
        }
    } else if (Constants.ACTION_UPDATE_WIDGET.equals(action)) {
        if (isConnected())
            setDetailsString(context);

        partiallyUpdateWidget(context, AppWidgetManager.getInstance(context),
                intent.getIntExtra(Constants.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID));
    }
}

From source file:mp.teardrop.PlaybackService.java

/**
 * Return the PlaybackService instance, creating one if needed.
 */// w w  w.  j a v  a2s .co m
public static PlaybackService get(Context context) {
    if (sInstance == null) {
        context.startService(new Intent(context, PlaybackService.class));

        while (sInstance == null) {
            try {
                synchronized (sWait) {
                    sWait.wait();
                }
            } catch (InterruptedException ignored) {
            }
        }
    }

    return sInstance;
}

From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java

private void joinSelectedContacts() {
    final Context context = getContext();
    final Intent intent = ContactSaveService.createJoinSeveralContactsIntent(context,
            getSelectedContactIdsArray());
    context.startService(intent);

    mActionBarAdapter.setSelectionMode(false);
}