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.ultrafunk.network_info.receiver.MobileDataStatusReceiver.java

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

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

    updateMobileDataViews = true;/*from  w w w . j  a  va2 s .  c  o  m*/

    telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    dataState = telephonyManager.getDataState();
    isMobileDataEnabled = MobileDataUtils.isMobileDataEnabled(context);
    isAirplaneModeOn = MobileDataUtils.isAirplaneModeOn(context);
    isMobileOutOfService = NetworkStateService.isMobileOutOfService();
    isDataRoaming = isDataRoaming(context);
    networkOperatorAndServiceProvider = getNetworkOperatorAndServiceProvider(context);
    dataUsageBytes = NetworkStateService
            .setGetDataUsageBytes(TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes());

    if (Constants.ACTION_DATA_CONNECTION_CHANGED.equals(action)
            || Constants.ACTION_DATA_STATE_CHANGED.equals(action)
            || Constants.ACTION_SERVICE_STATE_CHANGED.equals(action)) {
        // Needed to get around a known bug in Android 5.x: https://code.google.com/p/android/issues/detail?id=78924
        if ((dataState == TelephonyManager.DATA_CONNECTED) && (dataUsageBytes == 0)
                && !NetworkStateService.isWaitingForDataUsage()) {
            NetworkStateService.setWaitingForDataUsage(true);
            Intent serviceIntent = new Intent(context, NetworkStateService.class);
            serviceIntent.setAction(Constants.ACTION_DATA_CONNECTED);
            context.startService(serviceIntent);
        }

        partiallyUpdateWidgets(context);
    } else if (Constants.ACTION_DATA_USAGE_UPDATE.equals(action) || Intent.ACTION_SCREEN_ON.equals(action)) {
        partiallyUpdateWidgets(context);
    } else if (Constants.ACTION_UPDATE_WIDGET.equals(action)) {
        partiallyUpdateWidget(context, AppWidgetManager.getInstance(context),
                intent.getIntExtra(Constants.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID));
    }
}

From source file:com.google.samples.apps.iosched.ui.SessionDetailFragment.java

private void setupNotification() {
    Intent scheduleIntent;//from w ww  . j  a  va  2  s  .c  om
    final Context context = getActivity();

    // Schedule session notification
    if (UIUtils.getCurrentTime(context) < mSessionStart) {
        LOGD(TAG, "Scheduling notification about session start.");
        scheduleIntent = new Intent(SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, context,
                SessionAlarmService.class);
        scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionStart);
        scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionEnd);
        context.startService(scheduleIntent);
    } else {
        LOGD(TAG, "Not scheduling notification about session start, too late.");
    }

    // Schedule feedback notification
    if (Config.FEEDBACK_ENABLED && UIUtils.getCurrentTime(context) < mSessionEnd) {
        LOGD(TAG, "Scheduling notification about session feedback.");
        scheduleIntent = new Intent(SessionAlarmService.ACTION_SCHEDULE_FEEDBACK_NOTIFICATION, null, context,
                SessionAlarmService.class);
        scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ID, mSessionId);
        scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionStart);
        scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionEnd);
        scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_TITLE, mTitleString);
        scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ROOM, mRoomName);
        scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_SPEAKERS, mSpeakers);
        context.startService(scheduleIntent);
    } else {
        LOGD(TAG, "Not scheduling feedback notification, too late.");
    }
}

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

static public void alert(Context context, final long id) {
    final ExchangeService exchangeService = INSTANCE;
    checkExchangeServiceServiceRunning();
    if (id < 0) {
        log("ExchangeService alert");
        kick("ping ExchangeService");
    } else if (exchangeService == null) {
        context.startService(new Intent(context, ExchangeService.class));
    } else {//from   w w  w  . ja va 2 s.c  om
        final AbstractSyncService service = exchangeService.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 = "ExchangeService Alert: ";
            if (service.mMailbox != null) {
                threadName += service.mMailbox.mDisplayName;
            }
            new Thread(new Runnable() {
                public void run() {
                    Mailbox m = Mailbox.restoreMailboxWithId(exchangeService, 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 (Eas.USER_LOG) {
                            Log.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) {
                                exchangeService.releaseMailbox(id);
                            }
                            // Shutdown the connection manager; this should close all of our
                            // sockets and generate IOExceptions all around.
                            ExchangeService.shutdownConnectionManager();
                        }
                    }
                }
            }, threadName).start();
        }
    }
}

From source file:com.android.contacts.common.model.ContactLoader.java

/**
 * Posts a message to the contributing sync adapters that have opted-in, notifying them
 * that the contact has just been loaded
 *///from   w  w  w .  j  ava2 s.  c o  m
private void postViewNotificationToSyncAdapter() {
    Context context = getContext();
    for (RawContact rawContact : mContact.getRawContacts()) {
        final long rawContactId = rawContact.getId();
        if (mNotifiedRawContactIds.contains(rawContactId)) {
            continue; // Already notified for this raw contact.
        }
        mNotifiedRawContactIds.add(rawContactId);
        final AccountType accountType = rawContact.getAccountType(context);
        final String serviceName = accountType.getViewContactNotifyServiceClassName();
        final String servicePackageName = accountType.getViewContactNotifyServicePackageName();
        if (!TextUtils.isEmpty(serviceName) && !TextUtils.isEmpty(servicePackageName)) {
            final Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
            final Intent intent = new Intent();
            intent.setClassName(servicePackageName, serviceName);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, RawContacts.CONTENT_ITEM_TYPE);
            try {
                context.startService(intent);
            } catch (Exception e) {
                Log.e(TAG, "Error sending message to source-app", e);
            }
        }
    }
}

From source file:org.sirimangalo.meditationplus.ReceiverAlarm.java

@Override
public void onReceive(Context context, Intent pIntent) {
    Log.v(TAG, "ALARM: received alarm");

    NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (player != null) {
        Log.v(TAG, "Releasing media player...");
        try {/* w  ww.jav a2  s.c  om*/
            player.release();
            player = null;
        } catch (Exception e) {
            e.printStackTrace();
            player = null;
        } finally {
            // do nothing
        }
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    if (!prefs.getBoolean("set_alarm", false))
        return;

    player = new MediaPlayer();

    int setTime = pIntent.getIntExtra("period_time", 0);
    String medType = pIntent.getStringExtra("type");

    String title = context.getString(R.string.alarm_title);
    String desc = String.format(context.getString(R.string.alarm_desc), medType, setTime);

    Log.v(TAG, "Notification: " + desc);

    // Load the settings
    boolean led = prefs.getBoolean("alarm_led", true);
    boolean vibrate = prefs.getBoolean("alarm_vibrate", true);
    String notificationUri = prefs.getString("notification_uri",
            "android.resource://org.sirimangalo.meditationplus/" + R.raw.bell);

    Log.v(TAG, "notification uri: " + notificationUri);

    if (notificationUri.equals("system"))
        notificationUri = prefs.getString("SystemUri", "");
    else if (notificationUri.equals("file"))
        notificationUri = prefs.getString("FileUri", "");
    else if (notificationUri.equals("tts")) {
        notificationUri = "";
        final String ttsString = prefs.getString("tts_string", desc);
        Intent ttsIntent = new Intent(context, ServiceTTS.class);
        ttsIntent.putExtra("spoken_text", ttsString);
        context.startService(ttsIntent);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext())
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle(title).setContentText(desc);

    Uri uri = Uri.parse(notificationUri);
    mBuilder.setSound(uri);

    // Vibrate
    if (vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }
    // Have a light
    if (led) {

        String colorString = prefs.getString("alarm_led_color", "#FFFFFF");

        int color = 0xffffffff;

        try {
            color = Color.parseColor(colorString);
        } catch (Exception e) {

        }

        mBuilder.setLights(color, 300, 1000);
    }

    mBuilder.setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, ActivityMain.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(ActivityMain.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(0, mBuilder.build());

}

From source file:org.kontalk.service.msgcenter.MessageCenterService.java

/** Starts the push notifications unregistration process. */
public static void disablePushNotifications(Context context) {
    Intent i = new Intent(context, MessageCenterService.class);
    i.setAction(ACTION_PUSH_STOP);//from w  w  w.  jav  a  2s. co  m
    context.startService(i);
}

From source file:org.kontalk.service.msgcenter.MessageCenterService.java

/** Starts the push notifications registration process. */
public static void enablePushNotifications(Context context) {
    Intent i = new Intent(context, MessageCenterService.class);
    i.setAction(ACTION_PUSH_START);/*from ww w .  ja va2 s. c om*/
    context.startService(i);
}

From source file:com.vonglasow.michael.satstat.GpsEventReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);

    // some logic to use the pre-1.7 setting KEY_PREF_UPDATE_WIFI as a
    // fallback if KEY_PREF_UPDATE_NETWORKS is not set
    Set<String> fallbackUpdateNetworks = new HashSet<String>();
    if (sharedPref.getBoolean(Const.KEY_PREF_UPDATE_WIFI, false)) {
        fallbackUpdateNetworks.add(Const.KEY_PREF_UPDATE_NETWORKS_WIFI);
    }// w ww  .  j  av a 2s .  c  om
    Set<String> updateNetworks = sharedPref.getStringSet(Const.KEY_PREF_UPDATE_NETWORKS,
            fallbackUpdateNetworks);

    if (intent.getAction().equals(Const.GPS_ENABLED_CHANGE)
            || intent.getAction().equals(Const.GPS_ENABLED_CHANGE)) {
        //FIXME: why are we checking for the same intent twice? Should on of them be GPS_FIX_CHANGE?
        // an application has connected to GPS or disconnected from it, check if notification needs updating
        boolean notifyFix = sharedPref.getBoolean(Const.KEY_PREF_NOTIFY_FIX, false);
        boolean notifySearch = sharedPref.getBoolean(Const.KEY_PREF_NOTIFY_SEARCH, false);
        if (notifyFix || notifySearch) {
            boolean isRunning = false;
            ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (PasvLocListenerService.class.getName().equals(service.service.getClassName())) {
                    isRunning = true;
                }
            }
            if (!isRunning) {
                Intent startServiceIntent = new Intent(context, PasvLocListenerService.class);
                startServiceIntent.setAction(intent.getAction());
                startServiceIntent.putExtras(intent.getExtras());
                context.startService(startServiceIntent);
            }
        }
    } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)
            && updateNetworks.contains(Const.KEY_PREF_UPDATE_NETWORKS_WIFI)) {
        // change in WiFi connectivity, check if we are connected and need to refresh AGPS
        //FIXME: KEY_PREF_UPDATE_WIFI as fallback only
        NetworkInfo netinfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (netinfo == null)
            return;
        if (!netinfo.isConnected())
            return;
        //Toast.makeText(context, "WiFi is connected", Toast.LENGTH_SHORT).show();
        Log.i(this.getClass().getSimpleName(), "WiFi is connected");
        refreshAgps(context, true, false);
    } else if ((intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION))
            || (intent.getAction().equals(Const.AGPS_DATA_EXPIRED))) {
        // change in network connectivity or AGPS expiration timer fired
        boolean isAgpsExpired = false;
        if (intent.getAction().equals(Const.AGPS_DATA_EXPIRED)) {
            Log.i(this.getClass().getSimpleName(), "AGPS data expired, checking available networks");
            isAgpsExpired = true;
        }
        NetworkInfo netinfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (netinfo == null)
            return;
        if (!netinfo.isConnected())
            return;
        String type;
        if ((netinfo.getType() < ConnectivityManager.TYPE_MOBILE_MMS)
                || (netinfo.getType() > ConnectivityManager.TYPE_MOBILE_HIPRI)) {
            type = Integer.toString(netinfo.getType());
        } else {
            // specific mobile data connections will be treated as TYPE_MOBILE
            type = Const.KEY_PREF_UPDATE_NETWORKS_MOBILE;
        }
        if (!updateNetworks.contains(type))
            return;
        if (!isAgpsExpired)
            Log.i(this.getClass().getSimpleName(),
                    "Network of type " + netinfo.getTypeName() + " is connected");
        // Enforce the update interval if we were called by a network event
        // but not if we were called by a timer, because in that case the
        // check has already been done. (I am somewhat paranoid and don't
        // count on alarms not going off a few milliseconds too early.)
        refreshAgps(context, !isAgpsExpired, false);
    }
}

From source file:org.kontalk.service.msgcenter.MessageCenterService.java

public static void requestConnectionStatus(final Context context) {
    Intent i = new Intent(context, MessageCenterService.class);
    i.setAction(MessageCenterService.ACTION_CONNECTED);
    context.startService(i);
}

From source file:org.kontalk.service.msgcenter.MessageCenterService.java

public static void requestServerList(final Context context) {
    Intent i = new Intent(context, MessageCenterService.class);
    i.setAction(MessageCenterService.ACTION_SERVERLIST);
    context.startService(i);
}