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:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

/**
 * If user isn't already signed in, show sign in dialog. Else perform sync.
 *//*from  www. j a va2 s  .  co m*/
@Override
protected void initiateManual(Activity activity) {
    String authToken = preferences.getToken();
    OpencrxUtilities.INSTANCE.stopOngoing();

    // check if we have a token & it works
    if (authToken == null) {
        // display login-activity
        Intent intent = new Intent(activity, OpencrxLoginActivity.class);
        activity.startActivityForResult(intent, 0);
    } else {
        activity.startService(new Intent(null, null, activity, OpencrxBackgroundService.class));
    }
}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

private void startService(int requestCode) {
    if (hasPermission(ACCESS_FINE_LOCATION) && hasPermission(ACCESS_COARSE_LOCATION)) {
        Activity activity = cordova.getActivity();
        if (backgroundServiceIntent == null) {
            backgroundServiceIntent = new Intent(activity, BackgroundGeolocationService.class);
        }/*from   ww  w  .  ja  v  a 2s. com*/
        activity.startService(backgroundServiceIntent);
    } else {
        String[] permissions = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION };
        requestPermissions(requestCode, permissions);
    }
}

From source file:com.krayzk9s.imgurholo.ui.ImagesFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle item selection
    final Activity activity = getActivity();
    switch (item.getItemId()) {
    case R.id.action_download:
        Toast.makeText(activity,//from   w  w  w  .j a  va  2s.  c  o m
                String.format(getActivity().getResources().getString(R.string.toast_downloading), urls.size()),
                Toast.LENGTH_SHORT).show();
        Intent serviceIntent = new Intent(activity, DownloadService.class);
        serviceIntent.putParcelableArrayListExtra("ids", ids);
        if (albumId != null)
            serviceIntent.putExtra("albumName", albumId);
        else
            serviceIntent.putExtra("albumName", imageCall);
        activity.startService(serviceIntent);
        return true;
    case R.id.action_refresh:
        urls = new ArrayList<String>();
        ids = new ArrayList<JSONParcelable>();
        page = 0;
        makeGallery();
        return true;
    case R.id.action_copy:
        ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("imgur Link", "http://imgur.com/a/" + albumId);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(activity, R.string.toast_copied, Toast.LENGTH_SHORT).show();
        return true;
    case R.id.action_share:
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.putExtra(Intent.EXTRA_TEXT, "http://imgur.com/a/" + albumId);
        startActivity(intent);
        return true;
    case R.id.action_new:
        Intent i = new Intent(this.getActivity().getApplicationContext(), ImageSelectActivity.class);
        startActivityForResult(i, 1);
        //select image
        return true;
    case R.id.action_comments:
        if (galleryAlbumData != null) {
            CommentsAsync commentsAsync = new CommentsAsync(((ImgurHoloActivity) getActivity()),
                    galleryAlbumData);
            commentsAsync.execute();
            return true;
        } else
            return super.onOptionsItemSelected(item);
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

private void sync(CallbackContext callbackContext) {
    syncCallback = callbackContext;//from  w w w . java 2  s.com
    Activity activity = this.cordova.getActivity();

    EventBus eventBus = EventBus.getDefault();
    if (!eventBus.isRegistered(this)) {
        eventBus.register(this);
    }
    if (!BackgroundGeolocationService.isInstanceCreated()) {
        Intent syncIntent = new Intent(activity, BackgroundGeolocationService.class);
        syncIntent.putExtra("command", BackgroundGeolocationService.ACTION_SYNC);
        activity.startService(syncIntent);
    } else {
        final Bundle event = new Bundle();
        event.putString("name", BackgroundGeolocationService.ACTION_SYNC);
        event.putBoolean("request", true);
        postEventInBackground(event);
    }
}

From source file:com.hippo.ehviewer.ui.scene.DownloadsScene.java

@Override
public boolean onMenuItemClick(MenuItem item) {
    // Skip when in choice mode
    Activity activity = getActivity2();
    if (null == activity || null == mRecyclerView || mRecyclerView.isInCustomChoice()) {
        return false;
    }//from  w  w  w  .  j a va2  s. co  m

    int id = item.getItemId();
    switch (id) {
    case R.id.action_start_all: {
        Intent intent = new Intent(activity, DownloadService.class);
        intent.setAction(DownloadService.ACTION_START_ALL);
        activity.startService(intent);
        return true;
    }
    case R.id.action_stop_all: {
        if (null != mDownloadManager) {
            mDownloadManager.stopAllDownload();
        }
        return true;
    }
    }
    return false;
}

From source file:com.marianhello.cordova.bgloc.BackgroundGpsPlugin.java

public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    Activity activity = this.cordova.getActivity();
    Context context = activity.getApplicationContext();
    Boolean result = false;/* w ww  .  java 2s  . c  o m*/
    updateServiceIntent = new Intent(activity, LocationUpdateService.class);

    if (ACTION_START.equalsIgnoreCase(action) && !isEnabled) {
        result = true;
        if (params == null || headers == null) {
            callbackContext.error("Call configure before calling start");
        } else {
            IntentFilter intentFilter = new IntentFilter(Constant.FILTER);
            // LocalBroadcastManager.getInstance(activity).registerReceiver(mMessageReceiver, intentFilter);
            context.registerReceiver(mMessageReceiver, intentFilter);

            updateServiceIntent.putExtra("url", url);
            updateServiceIntent.putExtra("params", params);
            updateServiceIntent.putExtra("headers", headers);
            updateServiceIntent.putExtra("stationaryRadius", stationaryRadius);
            updateServiceIntent.putExtra("desiredAccuracy", desiredAccuracy);
            updateServiceIntent.putExtra("distanceFilter", distanceFilter);
            updateServiceIntent.putExtra("locationTimeout", locationTimeout);
            updateServiceIntent.putExtra("desiredAccuracy", desiredAccuracy);
            updateServiceIntent.putExtra("isDebugging", isDebugging);
            updateServiceIntent.putExtra("notificationTitle", notificationTitle);
            updateServiceIntent.putExtra("notificationText", notificationText);
            updateServiceIntent.putExtra("stopOnTerminate", stopOnTerminate);

            activity.startService(updateServiceIntent);
            isEnabled = true;
            Log.d(TAG, "bg service has been started");
        }
    } else if (ACTION_STOP.equalsIgnoreCase(action)) {
        // LocalBroadcastManager.getInstance(activity).unregisterReceiver(mMessageReceiver);
        context.unregisterReceiver(mMessageReceiver);

        isEnabled = false;
        result = true;
        activity.stopService(updateServiceIntent);
        callbackContext.success();
        Log.d(TAG, "bg service has been stopped");
    } else if (ACTION_CONFIGURE.equalsIgnoreCase(action)) {
        result = true;
        try {
            this.callbackContext = callbackContext;
            // Params.
            //    0       1       2           3               4                5               6            7           8                9               10              11
            //[params, headers, url, stationaryRadius, distanceFilter, locationTimeout, desiredAccuracy, debug, notificationTitle, notificationText, activityType, stopOnTerminate]
            this.params = data.getString(0);
            this.headers = data.getString(1);
            this.url = data.getString(2);
            this.stationaryRadius = data.getString(3);
            this.distanceFilter = data.getString(4);
            this.locationTimeout = data.getString(5);
            this.desiredAccuracy = data.getString(6);
            this.isDebugging = data.getString(7);
            this.notificationTitle = data.getString(8);
            this.notificationText = data.getString(9);
            this.stopOnTerminate = data.getString(11);
            Log.d(TAG, "bg service configured");
        } catch (JSONException e) {
            callbackContext.error("authToken/url required as parameters: " + e.getMessage());
        }
    } else if (ACTION_SET_CONFIG.equalsIgnoreCase(action)) {
        result = true;
        // TODO reconfigure Service
        callbackContext.success();
        Log.d(TAG, "bg service reconfigured");
    } else if (ACTION_LOCATION_ENABLED_CHECK.equalsIgnoreCase(action)) {
        Log.d(TAG, "location services enabled check");
        try {
            int isLocationEnabled = BackgroundGpsPlugin.isLocationEnabled(context) ? 1 : 0;
            callbackContext.success(isLocationEnabled);
        } catch (SettingNotFoundException e) {
            callbackContext.error("Location setting not found on this platform");
        }
    }

    return result;
}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

private void setEnabled(boolean value) {
    // Don't set a state that we're already in.
    Log.i(TAG, "- Enable: " + isEnabled + "  " + value);

    Activity activity = cordova.getActivity();
    boolean wasEnabled = isEnabled;
    isEnabled = value;/*from   w w w  .  j a  v a 2s.  c o m*/
    isMoving = null;

    Intent launchIntent = activity.getIntent();

    if (launchIntent.hasExtra("forceReload")) {
        if (launchIntent.hasExtra("location")) {
            try {
                JSONObject location = new JSONObject(launchIntent.getStringExtra("location"));
                onLocationChange(location);
            } catch (JSONException e) {
                Log.w(TAG, e);
            }
        }
    }

    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean("enabled", isEnabled);
    editor.apply();

    EventBus eventBus = EventBus.getDefault();
    if (isEnabled) {
        synchronized (eventBus) {
            if (!eventBus.isRegistered(this)) {
                eventBus.register(this);
            }
        }
        if (!BackgroundGeolocationService.isInstanceCreated()) {
            activity.startService(backgroundServiceIntent);
        } else {
            final Bundle event = new Bundle();
            if (!wasEnabled) {
                event.putString("name", BackgroundGeolocationService.ACTION_START);
            } else {
                event.putString("name", BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION);
            }
            event.putBoolean("request", true);
            postEvent(event);
            onStarted(event);
        }
    } else {
        Bundle event = new Bundle();
        event.putString("name", BackgroundGeolocationService.ACTION_STOP);
        event.putBoolean("request", true);
        postEvent(event);

        synchronized (eventBus) {
            if (eventBus.isRegistered(this)) {
                eventBus.unregister(this);
            }
        }
        //activity.stopService(backgroundServiceIntent);
        backgroundServiceIntent = null;
    }
}

From source file:com.silentcircle.contacts.group.GroupEditorFragment.java

/**
 * Saves or creates the group based on the mode, and if successful
 * finishes the activity. This actually only handles saving the group name.
 * @return true when successful//ww w. j  av  a 2  s  . c o m
 */
public boolean save() {
    if (!hasValidGroupName() || mStatus != Status.EDITING) {
        return false;
    }

    // If we are about to close the editor - there is no need to refresh the data
    getLoaderManager().destroyLoader(LOADER_EXISTING_MEMBERS);

    // If there are no changes, then go straight to onSaveCompleted()
    if (!hasNameChange() && !hasMembershipChange()) {
        onSaveCompleted(false, mGroupUri);
        return true;
    }

    mStatus = Status.SAVING;

    Activity activity = getActivity();
    // If the activity is not there anymore, then we can't continue with the save process.
    if (activity == null) {
        return false;
    }
    Intent saveIntent = null;
    if (Intent.ACTION_INSERT.equals(mAction)) {
        // Create array of raw contact IDs for contacts to add to the group
        long[] membersToAddArray = convertToArray(mListMembersToAdd);

        // Create the save intent to create the group and add members at the same time
        saveIntent = ScContactSaveService.createNewGroupIntent(activity, mGroupNameView.getText().toString(),
                membersToAddArray, activity.getClass(), GroupEditorActivity.ACTION_SAVE_COMPLETED);
    } else if (Intent.ACTION_EDIT.equals(mAction)) {
        // Create array of raw contact IDs for contacts to add to the group
        long[] membersToAddArray = convertToArray(mListMembersToAdd);

        // Create array of raw contact IDs for contacts to add to the group
        long[] membersToRemoveArray = convertToArray(mListMembersToRemove);

        // Create the update intent (which includes the updated group name if necessary)
        saveIntent = ScContactSaveService.createGroupUpdateIntent(activity, mGroupId, getUpdatedName(),
                membersToAddArray, membersToRemoveArray, activity.getClass(),
                GroupEditorActivity.ACTION_SAVE_COMPLETED);
    } else {
        throw new IllegalStateException("Invalid intent action type " + mAction);
    }
    activity.startService(saveIntent);
    return true;
}

From source file:com.hippo.ehviewer.ui.scene.DownloadsScene.java

@Override
public void onClickSecondaryFab(FabLayout view, FloatingActionButton fab, int position) {
    Context context = getContext2();
    Activity activity = getActivity2();
    EasyRecyclerView recyclerView = mRecyclerView;
    if (null == context || null == activity || null == recyclerView) {
        return;/*from  ww  w  .jav a  2  s. c om*/
    }

    if (0 == position) {
        recyclerView.checkAll();
    } else {
        List<DownloadInfo> list = mList;
        if (list == null) {
            return;
        }

        LongList gidList = null;
        List<DownloadInfo> downloadInfoList = null;
        boolean collectGid = position == 1 || position == 2 || position == 3; // Start, Stop, Delete
        boolean collectDownloadInfo = position == 3 || position == 4; // Delete or Move
        if (collectGid) {
            gidList = new LongList();
        }
        if (collectDownloadInfo) {
            downloadInfoList = new LinkedList<>();
        }

        SparseBooleanArray stateArray = recyclerView.getCheckedItemPositions();
        for (int i = 0, n = stateArray.size(); i < n; i++) {
            if (stateArray.valueAt(i)) {
                DownloadInfo info = list.get(stateArray.keyAt(i));
                if (collectDownloadInfo) {
                    downloadInfoList.add(info);
                }
                if (collectGid) {
                    gidList.add(info.gid);
                }
            }
        }

        switch (position) {
        case 1: { // Start
            Intent intent = new Intent(activity, DownloadService.class);
            intent.setAction(DownloadService.ACTION_START_RANGE);
            intent.putExtra(DownloadService.KEY_GID_LIST, gidList);
            activity.startService(intent);
            // Cancel check mode
            recyclerView.outOfCustomChoiceMode();
            break;
        }
        case 2: { // Stop
            if (null != mDownloadManager) {
                mDownloadManager.stopRangeDownload(gidList);
            }
            // Cancel check mode
            recyclerView.outOfCustomChoiceMode();
            break;
        }
        case 3: { // Delete
            CheckBoxDialogBuilder builder = new CheckBoxDialogBuilder(context,
                    getString(R.string.download_remove_dialog_message_2, gidList.size()),
                    getString(R.string.download_remove_dialog_check_text), Settings.getRemoveImageFiles());
            DeleteRangeDialogHelper helper = new DeleteRangeDialogHelper(downloadInfoList, gidList, builder);
            builder.setTitle(R.string.download_remove_dialog_title)
                    .setPositiveButton(android.R.string.ok, helper).show();
            break;
        }
        case 4: {// Move
            List<DownloadLabel> labelRawList = EhApplication.getDownloadManager(context).getLabelList();
            List<String> labelList = new ArrayList<>(labelRawList.size() + 1);
            labelList.add(getString(R.string.default_download_label_name));
            for (int i = 0, n = labelRawList.size(); i < n; i++) {
                labelList.add(labelRawList.get(i).getLabel());
            }
            String[] labels = labelList.toArray(new String[labelList.size()]);

            MoveDialogHelper helper = new MoveDialogHelper(labels, downloadInfoList);

            new AlertDialog.Builder(context).setTitle(R.string.download_move_dialog_title)
                    .setItems(labels, helper).show();
            break;
        }
        }
    }
}

From source file:net.etuldan.sparss.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        final Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from  ww w .  ja  v  a2 s. com

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        case R.id.menu_open_in_browser: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                    startActivity(browserIntent);
                }
            }
            break;
        }
        case R.id.menu_switch_full_original: {
            isChecked = !item.isChecked();
            item.setChecked(isChecked);
            if (mPreferFullText) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPreferFullText = false;
                        mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                    }
                });
            } else {
                Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
                final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

                if (alreadyMobilized) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mPreferFullText = true;
                            mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                        }
                    });
                } else if (!isRefreshing()) {
                    ConnectivityManager connectivityManager = (ConnectivityManager) activity
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                    // since we have acquired the networkInfo, we use it for basic checks
                    if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
                        activity.startService(new Intent(activity, FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showSwipeProgress();
                            }
                        });
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
            break;
        }
        default:
            break;
        }
    }

    return super.onOptionsItemSelected(item);
}