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:export.RunnerUpLive.java

@Override
public void liveLog(Context context, Location location, int type, double mElapsedDistanceMeter,
        double mElapsedTimeMillis) {
    int externalType = translateType(type);
    long elapsedDistanceMeter = Math.round(mElapsedDistanceMeter);
    Intent msgIntent = new Intent(context, LiveService.class);
    msgIntent.putExtra(LiveService.PARAM_IN_LAT, location.getLatitude());
    msgIntent.putExtra(LiveService.PARAM_IN_LONG, location.getLongitude());
    msgIntent.putExtra(LiveService.PARAM_IN_ALTITUDE, location.getAltitude());
    msgIntent.putExtra(LiveService.PARAM_IN_TYPE, externalType);
    msgIntent.putExtra(LiveService.PARAM_IN_ELAPSED_DISTANCE,
            formatter.formatDistance(Formatter.TXT_LONG, elapsedDistanceMeter));
    msgIntent.putExtra(LiveService.PARAM_IN_ELAPSED_TIME,
            formatter.formatElapsedTime(Formatter.TXT_LONG, Math.round(mElapsedTimeMillis / 1000)));
    msgIntent.putExtra(LiveService.PARAM_IN_PACE,
            formatter.formatPace(Formatter.TXT_SHORT, mElapsedTimeMillis / (1000 * mElapsedDistanceMeter)));
    msgIntent.putExtra(LiveService.PARAM_IN_USERNAME, username);
    msgIntent.putExtra(LiveService.PARAM_IN_PASSWORD, password);
    msgIntent.putExtra(LiveService.PARAM_IN_SERVERADRESS, postUrl);
    context.startService(msgIntent);
}

From source file:com.prey.events.factories.EventFactory.java

public static Event getEvent(Context ctx, Intent intent) {
    String message = "getEvent[" + intent.getAction() + "]";
    PreyLogger.d(message);//  ww w  .  j  a va  2  s. c  o m
    if (BOOT_COMPLETED.equals(intent.getAction())) {
        notification(ctx);
        if (PreyConfig.getPreyConfig(ctx).isSimChanged()) {
            JSONObject info = new JSONObject();
            try {
                info.put("new_phone_number", PreyTelephonyManager.getInstance(ctx).getLine1Number());
            } catch (Exception e) {
            }
            return new Event(Event.SIM_CHANGED, info.toString());
        } else {
            return new Event(Event.TURNED_ON);
        }
    }
    if (ACTION_SHUTDOWN.equals(intent.getAction())) {
        return new Event(Event.TURNED_OFF);
    }
    if (BATTERY_LOW.equals(intent.getAction())) {
        return new Event(Event.BATTERY_LOW);
    }
    if (CONNECTIVITY_CHANGE.equals(intent.getAction())) {
        JSONObject info = new JSONObject();
        int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
        PreyLogger.d("__wifiState:" + wifiState);
        try {
            boolean connected = false;
            if (!PreyConnectivityManager.getInstance(ctx).isWifiConnected()) {
                Bundle extras = intent.getExtras();
                if (extras != null) {
                    if ("connected".equals(extras.getString(ConnectivityManager.EXTRA_REASON))) {
                        connected = true;
                    }
                }
            }
            if (!PreyConnectivityManager.getInstance(ctx).isMobileConnected()) {
                info.put("connected", "mobile");
                if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
                    connected = true;
                }
            }
            if (connected) {
                try {
                    Thread.sleep(4000);
                } catch (Exception e) {
                }
                PreyConfig.getPreyConfig(ctx).registerC2dm();
                Intent intentFile = new Intent(ctx, FileretrievalService.class);
                ctx.startService(intentFile);
            }
        } catch (Exception e) {
        }
        return new Event(Event.WIFI_CHANGED, info.toString());
    }
    if (WIFI_STATE_CHANGED.equals(intent.getAction())) {
        JSONObject info = new JSONObject();
        int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
        PreyLogger.d("___wifiState:" + wifiState);

        try {
            if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
                info.put("connected", "wifi");
                try {
                    Thread.sleep(2000);
                } catch (Exception e) {
                }
                PreyConfig.getPreyConfig(ctx).registerC2dm();
                Intent intentFile = new Intent(ctx, FileretrievalService.class);
                ctx.startService(intentFile);
            }
        } catch (Exception e) {
        }
        return new Event(Event.WIFI_CHANGED, info.toString());
    }
    if (AIRPLANE_MODE.equals(intent.getAction())) {
        if (!isAirplaneModeOn(ctx)) {
            notification(ctx);
            boolean connected = false;
            if (!PreyConnectivityManager.getInstance(ctx).isWifiConnected()) {
                Bundle extras = intent.getExtras();
                if (extras != null) {
                    if ("connected".equals(extras.getString(ConnectivityManager.EXTRA_REASON))) {
                        connected = true;
                    }
                }
            }
            if (!PreyConnectivityManager.getInstance(ctx).isMobileConnected()) {
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
                        WifiManager.WIFI_STATE_UNKNOWN);
                if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
                    connected = true;
                }
            }
            if (connected) {
                PreyBetaController.startPrey(ctx);
                PreyConfig.getPreyConfig(ctx).registerC2dm();
                Intent intentFile = new Intent(ctx, FileretrievalService.class);
                ctx.startService(intentFile);
            }
        }
    }

    return null;
}

From source file:net.helff.wificonnector.WifiConnectivityReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Log.i(TAG, "action: " + intent.getAction());

    if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {

        Intent locationIntent = new LocationIntent();
        context.sendBroadcast(locationIntent);
    }//from  ww w  .j av  a  2 s . c  o m

    if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {

        NetworkInfo networkInfo = (NetworkInfo) intent
                .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

        Log.d(TAG, "got network_state_changed with detailed info: " + networkInfo == null ? "nothing"
                : networkInfo.getDetailedState().name());

        if (networkInfo != null && networkInfo.isConnected()
                && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            boolean autoConnect = prefs.getBoolean("autoConnect", false);

            Log.d(TAG, "triggering WifiConnectivityService with autoConnect=" + autoConnect);

            int command = autoConnect ? WifiConnectivityService.COMMAND_AUTO_UNLOCK_CONNECTION
                    : WifiConnectivityService.COMMAND_CHECK_CONNECTION;
            Intent msgIntent = new Intent(context, WifiConnectivityService.class);
            msgIntent.putExtra(WifiConnectivityService.INTENT_COMMAND, command);
            context.startService(msgIntent);
        }

    }
    if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
        Log.d(TAG, "triggering WifiConnectivityService state changed");

        Intent msgIntent = new Intent(context, WifiConnectivityService.class);
        msgIntent.putExtra(WifiConnectivityService.INTENT_COMMAND,
                WifiConnectivityService.COMMAND_REFRESH_STATUS);
        context.startService(msgIntent);
    }
}

From source file:com.chen.emailsync.SyncManager.java

static public void alert(Context context, final long id) {
    final SyncManager ssm = INSTANCE;
    checkSyncManagerRunning();/*from  w  w  w . jav  a  2  s  . c  om*/
    if (id < 0) {
        log("SyncServiceManager alert");
        kick("ping SyncServiceManager");
    } else if (ssm == null) {
        context.startService(new Intent(context, SyncManager.class));
    } else {
        final AbstractSyncService service = ssm.getRunningService(id);
        if (service != null) {
            // Handle alerts in a background thread, as we are typically called from a
            // broadcast receiver, and are therefore running in the UI thread
            String threadName = "SyncServiceManager Alert: ";
            if (service.mMailbox != null) {
                threadName += service.mMailbox.mDisplayName;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Mailbox m = Mailbox.restoreMailboxWithId(ssm, id);
                    if (m != null) {
                        // We ignore drafts completely (doesn't sync).  Changes in Outbox are
                        // handled in the checkMailboxes loop, so we can ignore these pings.
                        if (sUserLog) {
                            LogUtils.d(TAG, "Alert for mailbox " + id + " (" + m.mDisplayName + ")");
                        }
                        if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) {
                            String[] args = new String[] { Long.toString(m.mId) };
                            ContentResolver resolver = INSTANCE.mResolver;
                            resolver.delete(Message.DELETED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
                            resolver.delete(Message.UPDATED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
                            return;
                        }
                        service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey);
                        service.mMailbox = m;
                        // Send the alarm to the sync service
                        if (!service.alarm()) {
                            // A false return means that we were forced to interrupt the thread
                            // In this case, we release the mailbox so that we can start another
                            // thread to do the work
                            log("Alarm failed; releasing mailbox");
                            synchronized (sSyncLock) {
                                ssm.releaseMailbox(id);
                            }
                            // Shutdown the connection manager; this should close all of our
                            // sockets and generate IOExceptions all around.
                            SyncManager.shutdownConnectionManager();
                        }
                    }
                }
            }, threadName).start();
        }
    }
}

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Send an action to the events service.
 *
 * @param context the context./*from   ww w  . j a va2s. c  om*/
 * @param action  the action to send.
 */
private static void sendEventStreamAction(Context context, EventStreamService.StreamAction action) {
    Context appContext = context.getApplicationContext();

    Log.d(LOG_TAG, "sendEventStreamAction " + action);

    if (!isUserLogout(appContext)) {
        // Fix https://github.com/vector-im/vector-android/issues/230
        // Only start the service if a session is in progress, otherwise
        // starting the service is useless
        Intent killStreamService = new Intent(appContext, EventStreamService.class);
        killStreamService.putExtra(EventStreamService.EXTRA_STREAM_ACTION, action.ordinal());
        appContext.startService(killStreamService);
    } else {
        Log.d(LOG_TAG, "## sendEventStreamAction(): \"" + action + "\" action not sent - user logged out");
    }
}

From source file:com.asksven.betterbatterystats.data.KbReader.java

public KbData read(Context ctx) {
    if (LogSettings.DEBUG) {
        Log.i(TAG, "read called");
    }//from  w  w w .j av a2s  . co m
    if (m_cache == null) {
        if (LogSettings.DEBUG) {
            Log.i(TAG, "Cache is empty");
        }
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);

        // first check if cache is present and not outdated
        KbDbHelper myDB = KbDbHelper.getInstance(ctx);

        List<KbEntry> myEntries = myDB.fetchAllRows();

        // if cache exists and is not outdaten use it
        long cachedMillis = sharedPrefs.getLong("cache_updated", 0);
        long dateMillis = Calendar.getInstance().getTimeInMillis();
        boolean useCaching = sharedPrefs.getBoolean("cache_kb", true);

        // if cache is not empty, cache not older than 24 hours and caching is on
        if ((myEntries != null) && (myEntries.size() > 0) && (useCaching)
                && ((dateMillis - cachedMillis) < MAX_CACHE_AGE_MILLIS)) {
            m_cache = new KbData();
            m_cache.setEntries(myEntries);
        } else {
            if (LogSettings.DEBUG) {
                Log.i(TAG, "Starting service to retrieve KB");
            }
            // start async service to retrieve KB if not already running
            if (!KbReaderService.isTransactional()) {
                Intent serviceIntent = new Intent(ctx, KbReaderService.class);
                ctx.startService(serviceIntent);
            }
        }
    } else {
        if (LogSettings.DEBUG) {
            Log.i(TAG, "returning cached KB");
        }
    }
    return m_cache;
}

From source file:com.aware.Aware.java

/**
 * Starts a plugin. Expects the package name of the plugin.<br/>
 * It checks if the plugin does exist on the phone. If it doesn't, it will request the user to install it automatically.
 * @param context//from  w w w  . ja  v  a  2  s .c om
 * @param package_name
 */
public static void startPlugin(Context context, String package_name) {
    //Check if plugin is installed. If not, ask user to download it.
    Cursor is_installed = context.getContentResolver().query(Aware_Plugins.CONTENT_URI, null,
            Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null, null);
    if (is_installed != null && is_installed.moveToFirst()) {
        //We might just have it cached, but not installed
        if (isClassAvailable(context, package_name, "Plugin")) {
            //it's installed, start it!
            Intent plugin = new Intent();
            plugin.setClassName(package_name, package_name + ".Plugin");
            context.startService(plugin);
            if (Aware.DEBUG)
                Log.d(TAG, package_name + " started...");

            ContentValues rowData = new ContentValues();
            rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_ON);
            context.getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData,
                    Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null);
            is_installed.close();
            return;
        }
        is_installed.close();
    }

    HttpResponse response = new Https(awareContext)
            .dataGET("https://api.awareframework.com/index.php/plugins/get_plugin/" + package_name);
    if (response != null && response.getStatusLine().getStatusCode() == 200) {
        try {
            String data = EntityUtils.toString(response.getEntity());
            if (data.equals("[]"))
                return;

            JSONObject json_package = new JSONObject(data);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
            mBuilder.setSmallIcon(R.drawable.ic_stat_aware_plugin_dependency);
            mBuilder.setContentTitle("AWARE");
            mBuilder.setContentText("Plugin missing: " + json_package.getString("title") + ". Tap to install.");
            mBuilder.setDefaults(Notification.DEFAULT_ALL);
            mBuilder.setAutoCancel(true);

            Intent pluginIntent = new Intent(context, DownloadPluginService.class);
            pluginIntent.putExtra("package_name", package_name);
            pluginIntent.putExtra("is_update", false);

            PendingIntent clickIntent = PendingIntent.getService(context, 0, pluginIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(clickIntent);
            NotificationManager notManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notManager.notify(json_package.getInt("id"), mBuilder.build());

        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.mwebster.exchange.SyncManager.java

static public void alert(Context context, final long id) {
    final SyncManager syncManager = INSTANCE;
    checkSyncManagerServiceRunning();/* w ww . j  a v  a 2s.  c om*/
    if (id < 0) {
        kick("ping SyncManager");
    } else if (syncManager == null) {
        context.startService(new Intent(context, SyncManager.class));
    } else {
        final AbstractSyncService service = syncManager.mServiceMap.get(id);
        if (service != null) {
            // Handle alerts in a background thread, as we are typically called from a
            // broadcast receiver, and are therefore running in the UI thread
            new Thread(new Runnable() {
                public void run() {
                    Mailbox m = Mailbox.restoreMailboxWithId(syncManager, id);
                    if (m != null) {
                        // We ignore drafts completely (doesn't sync).  Changes in Outbox are
                        // handled in the checkMailboxes loop, so we can ignore these pings.
                        if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) {
                            String[] args = new String[] { Long.toString(m.mId) };
                            ContentResolver resolver = INSTANCE.mResolver;
                            resolver.delete(Message.DELETED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
                            resolver.delete(Message.UPDATED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
                            return;
                        }
                        service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey);
                        service.mMailbox = m;
                        // Send the alarm to the sync service
                        if (!service.alarm()) {
                            // A false return means that we were forced to interrupt the thread
                            // In this case, we release the mailbox so that we can start another
                            // thread to do the work
                            log("Alarm failed; releasing mailbox");
                            synchronized (sSyncLock) {
                                syncManager.releaseMailbox(id);
                            }
                            // Shutdown the connection manager; this should close all of our
                            // sockets and generate IOExceptions all around.
                            SyncManager.shutdownConnectionManager();
                        }
                    }
                }
            }).start();
        }
    }
}

From source file:com.android.exchange.SyncManager.java

static public void alert(Context context, final long id) {
    final SyncManager syncManager = INSTANCE;
    checkSyncManagerServiceRunning();/*from w  w w  .  j  a  v  a 2s  .  c o  m*/
    if (id < 0) {
        kick("ping SyncManager");
    } else if (syncManager == null) {
        context.startService(new Intent(context, SyncManager.class));
    } else {
        final AbstractSyncService service = syncManager.mServiceMap.get(id);
        if (service != null) {
            // Handle alerts in a background thread, as we are typically called from a
            // broadcast receiver, and are therefore running in the UI thread
            String threadName = "SyncManager Alert: ";
            if (service.mMailbox != null) {
                threadName += service.mMailbox.mDisplayName;
            }
            new Thread(new Runnable() {
                public void run() {
                    Mailbox m = Mailbox.restoreMailboxWithId(syncManager, id);
                    if (m != null) {
                        // We ignore drafts completely (doesn't sync).  Changes in Outbox are
                        // handled in the checkMailboxes loop, so we can ignore these pings.
                        if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) {
                            String[] args = new String[] { Long.toString(m.mId) };
                            ContentResolver resolver = INSTANCE.mResolver;
                            resolver.delete(Message.DELETED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
                            resolver.delete(Message.UPDATED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
                            return;
                        }
                        service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey);
                        service.mMailbox = m;
                        // Send the alarm to the sync service
                        if (!service.alarm()) {
                            // A false return means that we were forced to interrupt the thread
                            // In this case, we release the mailbox so that we can start another
                            // thread to do the work
                            log("Alarm failed; releasing mailbox");
                            synchronized (sSyncLock) {
                                syncManager.releaseMailbox(id);
                            }
                            // Shutdown the connection manager; this should close all of our
                            // sockets and generate IOExceptions all around.
                            SyncManager.shutdownConnectionManager();
                        }
                    }
                }
            }, threadName).start();
        }
    }
}

From source file:com.android.mail.utils.NotificationUtils.java

public static void sendSetNewEmailIndicatorIntent(Context context, final int unreadCount, final int unseenCount,
        final Account account, final Folder folder, final boolean getAttention) {
    LogUtils.i(LOG_TAG, "sendSetNewEmailIndicator account: %s, folder: %s",
            LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()),
            LogUtils.sanitizeName(LOG_TAG, folder.name));

    final Intent intent = new Intent(MailIntentService.ACTION_SEND_SET_NEW_EMAIL_INDICATOR);
    intent.setPackage(context.getPackageName()); // Make sure we only deliver this to ourselves
    intent.putExtra(EXTRA_UNREAD_COUNT, unreadCount);
    intent.putExtra(EXTRA_UNSEEN_COUNT, unseenCount);
    intent.putExtra(Utils.EXTRA_ACCOUNT, account);
    intent.putExtra(Utils.EXTRA_FOLDER, folder);
    intent.putExtra(EXTRA_GET_ATTENTION, getAttention);
    context.startService(intent);
}