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:org.durka.hallmonitor.CoreReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED) || intent.getAction().equals(QUICKBOOT_POWERON)
            || intent.getAction().equals(HTC_QUICKBOOT_POWERON)) {
        Log.d(LOG_TAG + ".boot", "Boot called.");
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        if (prefs.getBoolean("pref_enabled", false)) {
            Intent mIntent = new Intent(context, CoreService.class);
            context.startService(mIntent);
        }//from  w ww .j a  v  a 2s  . c  o  m
    }

    if (CoreStateManager.getInitialized()) {
        localContext = CoreStateManager.getContext();
        mStateManager = ((CoreApp) localContext).getStateManager();
    } else {
        return;
    }

    if (!mStateManager.getPreference().getBoolean("pref_enabled", false)) {
        return;
    }

    mStateManager.acquireCPUGlobal();

    if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {

        Log.d(LOG_TAG + ".screen", "Screen on event received.");

        if (mStateManager.getCoverClosed()) {
            Log.d(LOG_TAG + ".screen", "Cover is closed, display Default Activity.");
            mStateManager.setBlackScreenTime(0);
            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_LAUNCH_ACTIVITY);
            mStateManager.sendToCoreService(mIntent);
        } else {
            // Log.d(LOG_TAG + ".screen",
            // "Cover is open, free everything.");
            // mStateManager.freeDevice();
            Log.d(LOG_TAG + ".screen", "Cover is open, send to background.");
            Intent stbDAIntent = new Intent(CoreApp.DA_ACTION_SEND_TO_BACKGROUND);
            LocalBroadcastManager.getInstance(localContext).sendBroadcastSync(stbDAIntent);
        }

    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        Log.d(LOG_TAG + ".screen", "Screen off event received.");
        // mStateManager.freeDevice();

    } else if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
        Intent batteryDAIntent = new Intent(CoreApp.DA_ACTION_BATTERY_REFRESH);
        LocalBroadcastManager.getInstance(localContext).sendBroadcastSync(batteryDAIntent);

        Intent mIntent = new Intent(localContext, CoreService.class);
        mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_WAKEUP_DEVICE);
        mStateManager.sendToCoreService(mIntent);

    } else if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) {
        Intent batteryDAIntent = new Intent(CoreApp.DA_ACTION_BATTERY_REFRESH);
        LocalBroadcastManager.getInstance(localContext).sendBroadcastSync(batteryDAIntent);

        Intent mIntent = new Intent(localContext, CoreService.class);
        mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_WAKEUP_DEVICE);
        mStateManager.sendToCoreService(mIntent);

    } else if (intent.getAction().equals(ALARM_ALERT_ACTION)) {

        Log.d(LOG_TAG + ".alarm", "Alarm on event received.");

        // only take action if alarm controls are enabled
        if (mStateManager.getPreference().getBoolean("pref_alarm_controls", false)) {

            Log.d(LOG_TAG + ".alarm", "Alarm controls are enabled, taking action.");
            mStateManager.setAlarmFiring(true);

            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_INCOMMING_ALARM);
            mStateManager.sendToCoreService(mIntent);
        } else {
            Log.d(LOG_TAG + ".alarm", "Alarm controls are not enabled.");
        }

    } else if (intent.getAction().equals(ALARM_DONE_ACTION)) {

        Log.d(LOG_TAG + ".alarm", "Alarm done event received.");

        // only take action if alarm controls are enabled
        if (mStateManager.getPreference().getBoolean("pref_alarm_controls", false)) {
            Log.d(mStateManager.getPreference() + ".alarm", "alarm is over, cleaning up");
            mStateManager.setAlarmFiring(false);

            if (mStateManager.getCoverClosed()) {
                Intent mIntent = new Intent(localContext, CoreService.class);
                mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_LAUNCH_ACTIVITY);
                mStateManager.sendToCoreService(mIntent);
            }
        }
    } else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {

        if (mStateManager.getPreference().getBoolean("pref_phone_controls", false)) {
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            Log.d(LOG_TAG + ".phone", "phone state changed to " + state);
            if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                Intent mIntent;
                mStateManager.setPhoneRinging(true);
                mStateManager.setCallFrom(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
                Log.d(LOG_TAG, "call from " + mStateManager.getCallFrom());
                mIntent = new Intent(localContext, CoreService.class);
                mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_INCOMMING_CALL);
                mStateManager.sendToCoreService(mIntent);
            } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                Intent mIntent;
                mStateManager.setPhoneRinging(false);
                Log.d(LOG_TAG, "call is over, cleaning up");
                if (mStateManager.getCoverClosed()) {
                    mIntent = new Intent(localContext, CoreService.class);
                    mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_LAUNCH_ACTIVITY);
                    mStateManager.sendToCoreService(mIntent);
                }
            } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
            }
        } else {
            Log.d(LOG_TAG + ".phone", "phone controls are not enabled");
        }
    } else if (intent.getAction().equals(mStateManager.getActionCover())) {
        int state = intent.getIntExtra(EXTRA_LID_STATE, LID_ABSENT);
        Log.d(LOG_TAG + ".cover", "cover state changed to " + state);
        if (state == LID_CLOSED) {
            Log.d(LOG_TAG + ".cover", "Cover is close, enable Default Activity.");
            mStateManager.setCoverClosed(true);
            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_LAUNCH_ACTIVITY);
            mStateManager.sendToCoreService(mIntent);
        } else if (state == LID_OPEN) {
            // Log.d(LOG_TAG + ".cover",
            // "Cover is open, stopping Default Activity.");
            mStateManager.setCoverClosed(false);
            // mStateManager.freeDevice();
            Log.d(LOG_TAG + ".screen", "Cover is open, send to background.");
            Intent stbDAIntent = new Intent(CoreApp.DA_ACTION_SEND_TO_BACKGROUND);
            LocalBroadcastManager.getInstance(localContext).sendBroadcastSync(stbDAIntent);
            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_WAKEUP_DEVICE);
            mStateManager.sendToCoreService(mIntent);
        }

    } else if (intent.getAction().equals(TORCH_STATE_CHANGED)) {
        if (mStateManager.getPreference().getBoolean("pref_flash_controls", false)) {
            Log.d(LOG_TAG + ".torch", "torch state changed");
            Intent mIntent = new Intent(localContext, CoreService.class);
            mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_TORCH_STATE);
            if (intent.getIntExtra("state", 0) != 0) {
                mIntent.putExtra(CoreApp.CS_EXTRA_STATE, true);
            } else {
                mIntent.putExtra(CoreApp.CS_EXTRA_STATE, false);
            }
            mStateManager.sendToCoreService(mIntent);
        } else {
            Log.d(LOG_TAG + ".torch", "torch controls are not enabled.");
        }

    } else if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
        int state = intent.getExtras().getInt("state");
        Log.d(LOG_TAG + ".headset", "headset is " + (state == 0 ? "gone" : "here") + "!");
        Intent mIntent = new Intent(localContext, CoreService.class);
        mIntent.putExtra(CoreApp.CS_EXTRA_TASK, CoreApp.CS_TASK_HEADSET_PLUG);
        mStateManager.sendToCoreService(mIntent);

    } else if (intent.getAction().equals("org.durka.hallmonitor.debug")) {
        Log.d(LOG_TAG + "", "received debug intent");
        // test intent to show/hide a notification
        boolean showhide = false;
        switch (intent.getIntExtra("notif", 0)) {
        case 1:
            showhide = true;
            break;
        case 2:
            showhide = false;
            break;
        }
        if (showhide) {
            Notification.Builder mBuilder = new Notification.Builder(localContext)
                    .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Hall Monitor")
                    .setContentText("Debugging is fun!");

            NotificationManager mNotificationManager = (NotificationManager) localContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(42, mBuilder.build());
        } else {
            NotificationManager mNotificationManager = (NotificationManager) localContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.cancel(42);
        }
    }
    mStateManager.releaseCPUGlobal();
}

From source file:org.catrobat.catroid.utils.DownloadUtil.java

public void startDownload(Context context, String url, String programName) {
    programDownloadQueue.add(programName.toLowerCase(Locale.getDefault()));
    Intent downloadIntent = new Intent(context, ProjectDownloadService.class);
    downloadIntent.putExtra(ProjectDownloadService.RECEIVER_TAG, new DownloadProjectReceiver(new Handler()));
    downloadIntent.putExtra(ProjectDownloadService.DOWNLOAD_NAME_TAG, programName);
    downloadIntent.putExtra(ProjectDownloadService.URL_TAG, url);
    StatusBarNotificationManager manager = StatusBarNotificationManager.getInstance();
    int notificationId = manager.createDownloadNotification(context, programName);
    downloadIntent.putExtra(ProjectDownloadService.ID_TAG, notificationId);
    context.startService(downloadIntent);
}

From source file:com.android.contacts.ContactSaveService.java

/**
 * Returns true if the ContactSaveService was started successfully and false if an exception
 * was thrown and a Toast error message was displayed.
 *///from  w  w  w .j a va  2  s .c  om
public static boolean startService(Context context, Intent intent, int saveMode) {
    try {
        context.startService(intent);
    } catch (Exception exception) {
        final int resId;
        switch (saveMode) {
        case ContactEditorActivity.ContactEditor.SaveMode.SPLIT:
            resId = R.string.contactUnlinkErrorToast;
            break;
        case ContactEditorActivity.ContactEditor.SaveMode.RELOAD:
            resId = R.string.contactJoinErrorToast;
            break;
        case ContactEditorActivity.ContactEditor.SaveMode.CLOSE:
            resId = R.string.contactSavedErrorToast;
            break;
        default:
            resId = R.string.contactGenericErrorToast;
        }
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
        return false;
    }
    return true;
}

From source file:net.abcdroid.devfest12.ui.SessionDetailFragment.java

private void setupNotification() {
    // Schedule an alarm that fires a system notification when expires.
    final Context ctx = getActivity();
    Intent scheduleIntent = new Intent(SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, ctx,
            SessionAlarmService.class);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionBlockStart);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionBlockEnd);
    ctx.startService(scheduleIntent);
}

From source file:info.snowhow.plugin.GPSTrack.java

public void record(final String trackFile, final float precision, final long distanceChange,
        final long updateTime, final long updateTimeFast, final long speedLimit,
        final boolean adaptiveRecording, String trackName) {
    Context context = cordova.getActivity().getApplicationContext();
    Intent intent = new Intent(context, RecorderService.class);
    // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("fileName", trackFile);
    intent.putExtra("precision", precision);
    if (distanceChange > 0) {
        intent.putExtra("distance_change", distanceChange);
    }//w w  w  .  j  av  a 2  s  .  c o m
    if (updateTime > 0) {
        intent.putExtra("update_time", updateTime);
    }
    if (updateTimeFast > 0) {
        intent.putExtra("update_time_fast", updateTimeFast);
    }
    if (speedLimit > 0) {
        intent.putExtra("speed_limit", speedLimit);
    }
    intent.putExtra("adaptiveRecording", adaptiveRecording);
    intent.putExtra("trackName", trackName);
    Log.d(LOG_TAG, "in record ... should start intent now");
    context.startService(intent);
}

From source file:com.gcm.client.GcmHelper.java

/**
 * Un-subscribe from specific topics/*from   w  ww  . j a  va 2s. c  o  m*/
 *
 * @param context      An instance of the application {@link Context}
 * @param removeTopics list of topics which needs to be removed from subscription
 */
public boolean unSubscribeTopic(@NonNull Context context, @NonNull String[] removeTopics) {
    if (!initialized)
        init(context);
    if (removeTopics.length == 0)
        return false;
    for (String topic : removeTopics) {
        topics.remove(topic);
    }
    Intent intent = new Intent(context, RegistrationIntentService.class);
    intent.setAction(RegistrationIntentService.ACTION_UNSUBSCRIBE);
    intent.putExtra(RegistrationIntentService.EXTRA_TOPIC_LIST, removeTopics);
    context.startService(intent);
    return true;
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * Used to build and show a notification when Apollo is sent into the
 * background//from  w  w  w  .j a  va2s.  c  om
 *
 * @param context The {@link Context} to use.
 */
public static void notifyForegroundStateChanged(final Context context, boolean inForeground) {
    int old = sForegroundActivities;
    if (inForeground) {
        sForegroundActivities++;
    } else {
        sForegroundActivities--;
    }

    if (old == 0 || sForegroundActivities == 0) {
        final Intent intent = new Intent(context, MusicPlaybackService.class);
        intent.setAction(MusicPlaybackService.FOREGROUND_STATE_CHANGED);
        intent.putExtra(MusicPlaybackService.NOW_IN_FOREGROUND, sForegroundActivities != 0);
        context.startService(intent);
    }
}

From source file:com.cerema.cloud2.files.InstantUploadBroadcastReceiver.java

private void handleConnectivityAction(Context context, Intent intent) {
    if (!instantPictureUploadEnabled(context)) {
        Log_OC.d(TAG, "Instant upload disabled, don't upload anything");
        return;/* ww  w.j a v a 2 s.c  o  m*/
    }

    if (instantPictureUploadViaWiFiOnly(context) && !isConnectedViaWiFi(context)) {
        Account account = AccountUtils.getCurrentOwnCloudAccount(context);
        if (account == null) {
            Log_OC.w(TAG, "No account found for instant upload, aborting");
            return;
        }

        Intent i = new Intent(context, FileUploader.class);
        i.putExtra(FileUploader.KEY_ACCOUNT, account);
        i.putExtra(FileUploader.KEY_CANCEL_ALL, true);
        context.startService(i);
    }

    if (!intent.hasExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY) && isOnline(context)
            && (!instantPictureUploadViaWiFiOnly(context)
                    || (instantPictureUploadViaWiFiOnly(context) == isConnectedViaWiFi(context) == true))) {
        DbHandler db = new DbHandler(context);
        Cursor c = db.getAwaitingFiles();
        if (c.moveToFirst()) {
            do {
                if (instantPictureUploadViaWiFiOnly(context) && !isConnectedViaWiFi(context)) {
                    break;
                }

                String account_name = c.getString(c.getColumnIndex("account"));
                String file_path = c.getString(c.getColumnIndex("path"));
                File f = new File(file_path);
                if (f.exists()) {
                    Account account = new Account(account_name, MainApp.getAccountType());

                    String mimeType = null;
                    try {
                        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                                f.getName().substring(f.getName().lastIndexOf('.') + 1));

                    } catch (Throwable e) {
                        Log_OC.e(TAG,
                                "Trying to find out MIME type of a file without extension: " + f.getName());
                    }
                    if (mimeType == null)
                        mimeType = "application/octet-stream";

                    Intent i = new Intent(context, FileUploader.class);
                    i.putExtra(FileUploader.KEY_ACCOUNT, account);
                    i.putExtra(FileUploader.KEY_LOCAL_FILE, file_path);
                    i.putExtra(FileUploader.KEY_REMOTE_FILE,
                            FileStorageUtils.getInstantUploadFilePath(context, f.getName()));
                    i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
                    i.putExtra(FileUploader.KEY_INSTANT_UPLOAD, true);

                    // instant upload behaviour
                    i = addInstantUploadBehaviour(i, context);

                    context.startService(i);

                } else {
                    Log_OC.w(TAG, "Instant upload file " + f.getAbsolutePath() + " dont exist anymore");
                }
            } while (c.moveToNext());
        }
        c.close();
        db.close();
    }

}

From source file:com.farmerbb.taskbar.receiver.ShowHideTaskbarReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Intent taskbarIntent = new Intent(context, TaskbarService.class);
    Intent startMenuIntent = new Intent(context, StartMenuService.class);
    Intent dashboardIntent = new Intent(context, DashboardService.class);
    Intent notificationIntent = new Intent(context, NotificationService.class);

    SharedPreferences pref = U.getSharedPreferences(context);
    if (pref.getBoolean("is_hidden", false)) {
        pref.edit().putBoolean("is_hidden", false).apply();

        context.stopService(notificationIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && pref.getBoolean("freeform_hack", false)) {
            Intent intent2 = new Intent(context, DummyActivity.class);
            intent2.putExtra("start_freeform_hack", true);
            intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            context.startActivity(intent2);
        }/*from w ww.j a  va  2s . co  m*/

        context.startService(taskbarIntent);
        context.startService(startMenuIntent);
        context.startService(dashboardIntent);
        context.startService(notificationIntent);

    } else {
        pref.edit().putBoolean("is_hidden", true).apply();

        context.stopService(notificationIntent);

        if (!LauncherHelper.getInstance().isOnHomeScreen()) {
            context.stopService(taskbarIntent);
            context.stopService(startMenuIntent);
            context.stopService(dashboardIntent);

            IconCache.getInstance(context).clearCache();

            LocalBroadcastManager.getInstance(context)
                    .sendBroadcast(new Intent("com.farmerbb.taskbar.START_MENU_DISAPPEARING"));
        }

        context.startService(notificationIntent);
    }
}

From source file:com.conferenceengineer.android.iosched.ui.SessionDetailFragment.java

private void setupNotification() {
    // Schedule an alarm that fires a system notification when expires.
    final Context context = getActivity();
    Intent scheduleIntent = new Intent(SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, context,
            SessionAlarmService.class);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionBlockStart);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionBlockEnd);
    context.startService(scheduleIntent);
}