Example usage for android.app PendingIntent getService

List of usage examples for android.app PendingIntent getService

Introduction

In this page you can find the example usage for android.app PendingIntent getService.

Prototype

public static PendingIntent getService(Context context, int requestCode, @NonNull Intent intent,
        @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will start a service, like calling Context#startService Context.startService() .

Usage

From source file:com.alchemiasoft.book.service.BookActionService.java

@Override
protected void onHandleIntent(Intent intent) {
    final int notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, NOT_VALID_NOTIFICATION);
    // Cancelling any shown notification
    if (notificationId != NOT_VALID_NOTIFICATION) {
        Log.d(TAG_LOG, "Dismissing notification with id=" + notificationId);
        NotificationManagerCompat.from(this).cancel(notificationId);
    }/*from w w  w  .ja  v  a2  s  .co  m*/
    final long bookId = intent.getLongExtra(EXTRA_BOOK_ID, NOT_VALID_BOOK);
    if (bookId != NOT_VALID_BOOK) {
        final ContentResolver cr = getContentResolver();
        final Action action = Action.valueOf(intent.getAction());
        Log.d(TAG_LOG, "Performing action=" + action + " on book with id=" + bookId);
        final ContentValues cv = new ContentValues();
        switch (action) {
        case BUY:
            cv.put(BookDB.Book.OWNED, 1);
            if (cr.update(BookDB.Book.create(bookId), cv, null, null) == 1
                    && intent.getBooleanExtra(EXTRA_WEARABLE_INPUT, false)) {
                final Book book = getBook(bookId);
                if (book != null) {
                    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                    builder.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
                            .setContentTitle(getString(R.string.book_purchased))
                            .setContentText(book.getTitle());
                    builder.setContentIntent(PendingIntent.getActivity(this, 0,
                            HomeActivity.createFor(this, book), PendingIntent.FLAG_UPDATE_CURRENT));

                    // ONLY 4 WEARABLE(s)
                    final NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
                    wearableExtender
                            .setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.background));
                    // ACTION TO SELL A BOOK FROM A WEARABLE
                    final PendingIntent sellIntent = PendingIntent.getService(
                            this, 0, BookActionService.IntentBuilder.sell(this, book)
                                    .notificationId(NOTIFICATION_ID).wearableInput().build(),
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    wearableExtender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action_sell,
                            getString(R.string.action_sell), sellIntent).build());
                    // Finally extending the notification
                    builder.extend(wearableExtender);

                    NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, builder.build());
                }
            }
            break;
        case SELL:
            cv.put(BookDB.Book.OWNED, 0);
            if (cr.update(BookDB.Book.create(bookId), cv, null, null) == 1
                    && intent.getBooleanExtra(EXTRA_WEARABLE_INPUT, false)) {
                final Book book = getBook(bookId);
                if (book != null) {
                    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                    builder.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
                            .setContentTitle(getString(R.string.book_sold)).setContentText(book.getTitle());
                    builder.setContentIntent(PendingIntent.getActivity(this, 0,
                            HomeActivity.createFor(this, book), PendingIntent.FLAG_UPDATE_CURRENT));

                    NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, builder.build());
                }
            }
            break;
        case ADD_NOTE:
            final CharSequence notes = getExtraNotes(intent);
            if (!TextUtils.isEmpty(notes)) {
                cv.put(BookDB.Book.NOTES, notes.toString());
                cr.update(BookDB.Book.create(bookId), cv, null, null);
            }
            break;
        default:
            break;
        }
    }
}

From source file:com.mishiranu.dashchan.content.service.PostingService.java

@Override
public void run() {
    boolean interrupted = false;
    while (true) {
        TaskState taskState = null;/*w ww.  java2s.c o m*/
        if (!interrupted) {
            try {
                taskState = notificationsQueue.take();
            } catch (InterruptedException e) {
                interrupted = true;
            }
        }
        if (interrupted) {
            taskState = notificationsQueue.poll();
        }
        if (taskState == null) {
            return;
        }
        if (taskState.cancel) {
            notificationManager.cancel(taskState.notificationId);
        } else {
            Notification.Builder builder = taskState.builder;
            if (taskState.first) {
                builder.setOngoing(true);
                builder.setSmallIcon(android.R.drawable.stat_sys_upload);
                PendingIntent cancelIntent = PendingIntent.getService(
                        this, taskState.notificationId, new Intent(this, PostingService.class)
                                .setAction(ACTION_CANCEL_POSTING).putExtra(EXTRA_KEY, taskState.key),
                        PendingIntent.FLAG_UPDATE_CURRENT);
                Context themedContext = new ContextThemeWrapper(this, R.style.Theme_Special_Notification);
                ViewUtils.addNotificationAction(builder, this,
                        ResourceUtils.getResourceId(themedContext, R.attr.notificationCancel, 0),
                        getString(android.R.string.cancel), cancelIntent);
                if (C.API_LOLLIPOP) {
                    setNotificationColor(builder);
                }
            }
            boolean progressMode = taskState.task.isProgressMode();
            switch (taskState.progressState) {
            case CONNECTING: {
                if (progressMode) {
                    builder.setProgress(1, 0, true);
                }
                builder.setContentTitle(getString(R.string.message_sending));
                break;
            }
            case SENDING: {
                if (progressMode) {
                    builder.setProgress(taskState.progressMax, taskState.progress, taskState.progressMax <= 0);
                    builder.setContentTitle(getString(R.string.message_sending_index_format,
                            taskState.attachmentIndex + 1, taskState.attachmentsCount));
                } else {
                    builder.setContentTitle(getString(R.string.message_sending));
                }
                break;
            }
            case PROCESSING: {
                if (progressMode) {
                    builder.setProgress(1, 1, false);
                }
                builder.setContentTitle(getString(R.string.message_processing_data));
                break;
            }
            }
            builder.setContentText(taskState.text);
            notificationManager.notify(taskState.notificationId, builder.build());
        }
    }
}

From source file:com.janacare.walkmeter.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    vPref = getApplicationContext().getSharedPreferences(ActivityUtils.SHARED_PREFERENCES,
            Context.MODE_PRIVATE);

    // Set the main layout

    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.pedometer);/*from  w  w w.  j av  a 2  s  .  com*/

    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);

    showStepsToday = (TextView) findViewById(R.id.tvStepsToday);
    showStepsYesterday = (TextView) findViewById(R.id.tvStepsYesterday);
    showStepsHighest = (TextView) findViewById(R.id.tvStepsHighest);
    btnCount = (Button) findViewById(R.id.btnCount);
    tvwindow_title = (TextView) findViewById(R.id.tvwindow_tite);
    tvtodayAfter = (TextView) findViewById(R.id.tvStepsTodayAfter);
    headToday = (TextView) findViewById(R.id.tvStepsToday1);
    headYesterday = (TextView) findViewById(R.id.tvStepsYesterday2);
    headHighest = (TextView) findViewById(R.id.tvStepsHighest3);

    Typeface regular = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
    Typeface thin = Typeface.createFromAsset(getAssets(), "Roboto-Thin.ttf");

    tvwindow_title.setTypeface(regular);
    showStepsToday.setTypeface(thin);
    showStepsYesterday.setTypeface(thin);
    showStepsHighest.setTypeface(thin);

    tvtodayAfter.setTypeface(regular);
    headToday.setTypeface(regular);
    headYesterday.setTypeface(regular);
    headHighest.setTypeface(regular);
    btnCount.setTypeface(regular);

    int i = vPref.getInt(Constants.KEY_STEPS_TODAY, 0);
    int j = vPref.getInt("steps_yesterday", 0);
    int k = vPref.getInt("minutes_highest", i);
    Log.d("step  in", Long.toString(i));
    Log.d("show steps", "showStepsToday: " + showStepsToday);

    showStepsToday.setText(Integer.toString(i));
    showStepsYesterday.setText(Integer.toString(j));
    showStepsHighest.setText(Integer.toString(k));

    mBroadcastManager = LocalBroadcastManager.getInstance(this);

    // Create a new Intent filter for the broadcast receiver
    mBroadcastFilter = new IntentFilter(ActivityUtils.ACTION_REFRESH_STATUS_LIST);
    mBroadcastFilter.addCategory(ActivityUtils.CATEGORY_LOCATION_SERVICES);

    // Get detection requester and remover objects
    mDetectionRequester = new DetectionRequester(this);
    mDetectionRemover = new DetectionRemover(this);

    // Create a new LogFile object
    mLogFile = LogFile.getInstance(this);

    btnCount.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Log.d(TAG, "before btn action" + vPref.getBoolean("btnFlag", false));

            Editor editor = vPref.edit();

            if (!vPref.getBoolean("btnFlag", false)) {

                Log.d(TAG, "first time btn pressed");
                if (!servicesConnected()) {
                    return;
                }
                mRequestType = ActivityUtils.REQUEST_TYPE.ADD;
                mDetectionRequester.requestUpdates();
                btnCount.setText("Stop Counting");

                editor.putBoolean("btnFlag", true);
                editor.commit();

                Log.d(TAG, "" + vPref.getBoolean("btnFlag", false));
            } else {

                Log.d(TAG, "in onClick after btn shows stop counting");
                if (!servicesConnected()) {

                    return;
                }

                mRequestType = ActivityUtils.REQUEST_TYPE.REMOVE;
                PendingIntent pendingIntent = mDetectionRequester.getRequestPendingIntent();

                if (pendingIntent == null) {
                    Intent intent = new Intent(getApplicationContext(), ActivityRecognitionIntentService.class);
                    pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                }

                if (pendingIntent != null) {
                    // Pass the remove request to the remover object
                    mDetectionRemover.removeUpdates(pendingIntent);
                    pendingIntent.cancel();
                }

                editor.putBoolean("btnFlag", false);
                editor.commit();
                btnCount.setText("Start Counting!");
            }

        }
    });

}

From source file:com.brayanarias.alarmproject.receiver.AlarmReceiver.java

public static PendingIntent createPendingIntent(Context context, Alarm alarm) {
    PendingIntent pendingIntent = null;//w  ww.ja  va  2  s.co m
    try {
        Intent intent = new Intent(context, AlarmService.class);
        intent.putExtra(Constant.alarmIdKey, alarm.getId());
        intent.putExtra(Constant.alarmNameKey, alarm.getName());
        intent.putExtra(Constant.alarmHourKey, alarm.getHour());
        intent.putExtra(Constant.alarmMinuteKey, alarm.getMinute());
        intent.putExtra(Constant.alarmToneKey, alarm.getTone());
        intent.putExtra(Constant.alarmHourFormattedKey, alarm.getHourFormatted());
        intent.putExtra(Constant.alarmVibrateKey, alarm.getVibrate());
        intent.putExtra(Constant.alarmAmPmKey, alarm.getAmPm());
        intent.putExtra(Constant.alarmSoundHolidayKey, alarm.getOnHoliday());
        intent.putExtra(Constant.alarmDaysKey, alarm.getDaysOfAlamr());
        intent.putExtra(Constant.alarmDeleteAfterKey, alarm.getDeleteOnSound());
        intent.putExtra(Constant.alarmPostponeKey, alarm.getPostpone());
        pendingIntent = PendingIntent.getService(context, alarm.getId(), intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    } catch (Exception e) {
        Log.e(tag, e.getLocalizedMessage(), e);
    }
    return pendingIntent;
}

From source file:com.perfilyev.vkmessengerlite.MessagingService.java

private NotificationCompat.Action createReplyAction(long peerId, PendingIntent mainPendingIntent) {
    String replyLabel = getString(R.string.reply_label);

    Bundle extras = new Bundle();
    extras.putLong(MessagingService.EXTRA_PEER_ID, peerId);

    RemoteInput remoteInput = new RemoteInput.Builder(MessagingService.EXTRA_REPLY).addExtras(extras)
            .setLabel(replyLabel).build();
    PendingIntent replyActionPendingIntent;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Intent intent = new Intent(this, MessagingService.class);
        intent.setAction(MessagingService.ACTION_REPLY);
        replyActionPendingIntent = PendingIntent.getService(this, 0, intent, 0);
    } else {/*  w w w.ja  v a  2 s  .c o m*/
        // TODO: 22.10.2016 add fallback to activity
        replyActionPendingIntent = mainPendingIntent;
    }

    return new NotificationCompat.Action.Builder(R.drawable.ic_reply, replyLabel, replyActionPendingIntent)
            .addRemoteInput(remoteInput).setAllowGeneratedReplies(true).build();
}

From source file:com.android.deskclock.alarms.AlarmNotifications.java

public static void showMissedNotification(Context context, AlarmInstance instance) {
    LogUtils.v("Displaying missed notification for alarm instance: " + instance.mId);

    String label = instance.mLabel;
    String alarmTime = AlarmUtils.getFormattedTime(context, instance.getAlarmTime());
    NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.alarm_missed_title))
            .setContentText(instance.mLabel.isEmpty() ? alarmTime
                    : context.getString(R.string.alarm_missed_text, alarmTime, label))
            .setSmallIcon(R.drawable.stat_notify_alarm).setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);// w ww .j a  va  2s  .  co m

    final int hashCode = instance.hashCode();

    // Setup dismiss intent
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE);
    notification.setDeleteIntent(
            PendingIntent.getService(context, hashCode, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content intent
    Intent showAndDismiss = AlarmInstance.createIntent(context, AlarmStateManager.class, instance.mId);
    showAndDismiss.putExtra(EXTRA_NOTIFICATION_ID, hashCode);
    showAndDismiss.setAction(AlarmStateManager.SHOW_AND_DISMISS_ALARM_ACTION);
    notification.setContentIntent(
            PendingIntent.getBroadcast(context, hashCode, showAndDismiss, PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    nm.notify(hashCode, notification.build());
}

From source file:com.androidinspain.deskclock.data.TimerNotificationBuilder.java

public Notification build(Context context, NotificationModel nm, List<Timer> unexpired) {
    final Timer timer = unexpired.get(0);
    final int count = unexpired.size();

    // Compute some values required below.
    final boolean running = timer.isRunning();
    final Resources res = context.getResources();

    final long base = getChronometerBase(timer);
    final String pname = context.getPackageName();

    final List<Action> actions = new ArrayList<>(2);

    final CharSequence stateText;
    if (count == 1) {
        if (running) {
            // Single timer is running.
            if (TextUtils.isEmpty(timer.getLabel())) {
                stateText = res.getString(com.androidinspain.deskclock.R.string.timer_notification_label);
            } else {
                stateText = timer.getLabel();
            }//from   www  .  j  a  v a 2 s. c  om

            // Left button: Pause
            final Intent pause = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_PAUSE_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon1 = com.androidinspain.deskclock.R.drawable.ic_pause_24dp;
            final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_pause);
            final PendingIntent intent1 = Utils.pendingServiceIntent(context, pause);
            actions.add(new Action.Builder(icon1, title1, intent1).build());

            // Right Button: +1 Minute
            final Intent addMinute = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_ADD_MINUTE_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon2 = com.androidinspain.deskclock.R.drawable.ic_add_24dp;
            final CharSequence title2 = res.getText(com.androidinspain.deskclock.R.string.timer_plus_1_min);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, addMinute);
            actions.add(new Action.Builder(icon2, title2, intent2).build());

        } else {
            // Single timer is paused.
            stateText = res.getString(com.androidinspain.deskclock.R.string.timer_paused);

            // Left button: Start
            final Intent start = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_START_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon1 = com.androidinspain.deskclock.R.drawable.ic_start_24dp;
            final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.sw_resume_button);
            final PendingIntent intent1 = Utils.pendingServiceIntent(context, start);
            actions.add(new Action.Builder(icon1, title1, intent1).build());

            // Right Button: Reset
            final Intent reset = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_RESET_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon2 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp;
            final CharSequence title2 = res.getText(com.androidinspain.deskclock.R.string.sw_reset_button);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, reset);
            actions.add(new Action.Builder(icon2, title2, intent2).build());
        }
    } else {
        if (running) {
            // At least one timer is running.
            stateText = res.getString(com.androidinspain.deskclock.R.string.timers_in_use, count);
        } else {
            // All timers are paused.
            stateText = res.getString(com.androidinspain.deskclock.R.string.timers_stopped, count);
        }

        final Intent reset = TimerService.createResetUnexpiredTimersIntent(context);

        @DrawableRes
        final int icon1 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp;
        final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_reset_all);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, reset);
        actions.add(new Action.Builder(icon1, title1, intent1).build());
    }

    // Intent to load the app and show the timer when the notification is tapped.
    final Intent showApp = new Intent(context, TimerService.class).setAction(TimerService.ACTION_SHOW_TIMER)
            .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId())
            .putExtra(Events.EXTRA_EVENT_LABEL, com.androidinspain.deskclock.R.string.label_notification);

    final PendingIntent pendingShowApp = PendingIntent.getService(context, REQUEST_CODE_UPCOMING, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    final Builder notification = new NotificationCompat.Builder(context).setOngoing(true).setLocalOnly(true)
            .setShowWhen(false).setAutoCancel(false).setContentIntent(pendingShowApp)
            .setPriority(Notification.PRIORITY_HIGH).setCategory(NotificationCompat.CATEGORY_ALARM)
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_timer)
            .setSortKey(nm.getTimerNotificationSortKey()).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background));

    for (Action action : actions) {
        notification.addAction(action);
    }

    if (Utils.isNOrLater()) {
        notification.setCustomContentView(buildChronometer(pname, base, running, stateText))
                .setGroup(nm.getTimerNotificationGroupKey());
    } else {
        final CharSequence contentTextPreN;
        if (count == 1) {
            contentTextPreN = TimerStringFormatter.formatTimeRemaining(context, timer.getRemainingTime(),
                    false);
        } else if (running) {
            final String timeRemaining = TimerStringFormatter.formatTimeRemaining(context,
                    timer.getRemainingTime(), false);
            contentTextPreN = context.getString(com.androidinspain.deskclock.R.string.next_timer_notif,
                    timeRemaining);
        } else {
            contentTextPreN = context.getString(com.androidinspain.deskclock.R.string.all_timers_stopped_notif);
        }

        notification.setContentTitle(stateText).setContentText(contentTextPreN);

        final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final Intent updateNotification = TimerService.createUpdateNotificationIntent(context);
        final long remainingTime = timer.getRemainingTime();
        if (timer.isRunning() && remainingTime > MINUTE_IN_MILLIS) {
            // Schedule a callback to update the time-sensitive information of the running timer
            final PendingIntent pi = PendingIntent.getService(context, REQUEST_CODE_UPCOMING,
                    updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

            final long nextMinuteChange = remainingTime % MINUTE_IN_MILLIS;
            final long triggerTime = SystemClock.elapsedRealtime() + nextMinuteChange;
            TimerModel.schedulePendingIntent(am, triggerTime, pi);
        } else {
            // Cancel the update notification callback.
            final PendingIntent pi = PendingIntent.getService(context, 0, updateNotification,
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE);
            if (pi != null) {
                am.cancel(pi);
                pi.cancel();
            }
        }
    }

    return notification.build();
}

From source file:org.ambientdynamix.core.HomeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    Log.v(TAG, "Activity State: onCreate()");
    super.onCreate(savedInstanceState);
    // Set our static reference
    activity = this;
    setContentView(R.layout.home_tab);/*  w  ww . j av a  2 s  .  c  om*/

    updateCheck();

    points = new HashSet<>();
    mMixpanel = MixpanelAPI.getInstance(this, Constants.MIXPANEL_TOKEN);

    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map_main));

    // Check if we were successful in obtaining the map.
    if (mMap == null) {
        // check if google play service in the device is not available or out-dated.
        GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        // nothing anymore, cuz android will take care of the rest (to remind user to update google play service).
    }

    // Construct the data source
    sensorMeasurements = new ArrayList<>();
    // Create the adapter to convert the array to views
    sensorMeasurementAdapter = new SensorMeasurementAdapter(this, sensorMeasurements);
    // Attach the adapter to a ListView
    final TwoWayView listView = (TwoWayView) findViewById(R.id.lvItems);
    listView.setOrientation(TwoWayView.Orientation.VERTICAL);
    listView.setPadding(0, 0, 0, 0);
    listView.setItemMargin(0);
    listView.setAdapter(sensorMeasurementAdapter);

    //Disable for now
    final Intent activityRecognitionIntent = new Intent(this, ActivityRecognitionService.class);
    activityRecognitionPendingIntent = PendingIntent.getService(getApplicationContext(), 0,
            activityRecognitionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

    pendingSendButton = (Button) findViewById(R.id.send_pending_now);
    pendingSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AsyncReportOnServerTask().execute();
            try {
                final JSONObject props = new JSONObject();
                props.put("count", DynamixService.getDataStorageSize());
                //mMixpanel.track("send-stored-readings", props);
            } catch (JSONException ignore) {
            }

        }
    });

    // Setup an state refresh timer, which periodically updates application
    // state in the appList
    final Timer refresher = new Timer(true);
    final TimerTask t = new TimerTask() {
        @Override
        public void run() {

            refreshData();
        }
    };
    refresher.scheduleAtFixedRate(t, 0, 5000);

    phoneIdTv = (TextView) this.findViewById(R.id.deviceId_label);

    expDescriptionTv = (TextView) this.findViewById(R.id.experiment_description);

    if (mMap.getMap() != null) {
        mMap.getMap().setMyLocationEnabled(true);
        mMap.getMap().getUiSettings().setAllGesturesEnabled(false);
        mMap.getMap().getUiSettings().setMyLocationButtonEnabled(false);
    }
}

From source file:com.darshancomputing.BatteryIndicatorPro.BatteryInfoService.java

@Override
public void onCreate() {
    res = getResources();//from  w  w  w  . j a  va 2  s  .co  m
    str = new Str(res);
    log_db = new LogDatabase(this);

    info = new BatteryInfo();

    messenger = new Messenger(new MessageHandler());
    clientMessengers = new java.util.HashSet<Messenger>();

    predictor = new Predictor(this);
    bl = BatteryLevel.getInstance(this, BatteryLevel.SIZE_NOTIFICATION);
    cwbg = new CircleWidgetBackground(this);

    alarms = new AlarmDatabase(this);

    mNotificationManager = NotificationManagerCompat.from(this);
    mainNotificationB = new NotificationCompat.Builder(this);

    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    loadSettingsFiles();
    sdkVersioning();

    currentHack = CurrentHack.getInstance(this);
    currentHack.setPreferFS(settings.getBoolean(SettingsActivity.KEY_CURRENT_HACK_PREFER_FS,
            res.getBoolean(R.bool.default_prefer_fs_current_hack)));

    Intent currentInfoIntent = new Intent(this, BatteryInfoActivity.class).putExtra(EXTRA_CURRENT_INFO, true);
    currentInfoPendingIntent = PendingIntent.getActivity(this, RC_MAIN, currentInfoIntent, 0);

    Intent updatePredictorIntent = new Intent(this, BatteryInfoService.class);
    updatePredictorIntent.putExtra(EXTRA_UPDATE_PREDICTOR, true);
    updatePredictorPendingIntent = PendingIntent.getService(this, 0, updatePredictorIntent, 0);

    Intent alarmsIntent = new Intent(this, BatteryInfoActivity.class).putExtra(EXTRA_EDIT_ALARMS, true);
    alarmsPendingIntent = PendingIntent.getActivity(this, RC_ALARMS, alarmsIntent, 0);

    widgetManager = AppWidgetManager.getInstance(this);

    Class[] appWidgetProviders = { BatteryInfoAppWidgetProvider.class, /* Circle widget! */
            FullAppWidgetProvider.class };

    for (int i = 0; i < appWidgetProviders.length; i++) {
        int[] ids = widgetManager.getAppWidgetIds(new ComponentName(this, appWidgetProviders[i]));

        for (int j = 0; j < ids.length; j++) {
            widgetIds.add(ids[j]);
        }
    }

    Intent bc_intent = registerReceiver(mBatteryInfoReceiver, batteryChanged);
    info.load(bc_intent, sp_service);
}

From source file:com.terminal.ide.TermService.java

@Override
public void onCreate() {
    compat = new ServiceForegroundCompat(this);
    mTermSessions = new ArrayList<TermSession>();

    /**//from   ww w . j a  v a  2  s . c  o  m
     * ??
     * @author wanghao
     * @date 2015-3-27
     * ???Activity
     */
    //?intent
    //warning??start.class
    //?mainActivity
    Intent openMainActivityIntent = new Intent(this, mainAvtivity.class);
    Intent openTerminalActivityIntent = new Intent(this, Term.class);
    openTerminalActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    openMainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Intent exitTerminalIntent = new Intent(this, ExitService.class);
    Notification sessionBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getText(R.string.application_terminal))
            .setContentText(getText(R.string.service_notify_text))
            .setContentIntent(PendingIntent.getActivity(this, 0, openMainActivityIntent, 0))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(getText(R.string.service_notify_text)))
            .addAction(R.drawable.ic_action_iconfont_terminal, getText(R.string.notification_open_termianl),
                    PendingIntent.getActivity(this, 0, openTerminalActivityIntent,
                            Intent.FLAG_ACTIVITY_CLEAR_TOP))
            .addAction(R.drawable.ic_action_iconfont_exit, getText(R.string.notification_exit_app),
                    PendingIntent.getService(this, 0, exitTerminalIntent, 0))
            .setOngoing(true).build();
    compat.startForeground(RUNNING_NOTIFICATION, sessionBuilder);

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mPrefs.registerOnSharedPreferenceChangeListener(this);
    mHardKeys.setKeyMappings(mPrefs);

    //Setup the Hard Key Mappings..
    mSettings = new TermSettings(mPrefs);

    //Need to set the HOME Folder and Bash startup..
    //Sometime getfilesdir return NULL ?
    mSessionInit = false;
    File home = getFilesDir();
    if (home != null) {
        initSessions(home);
    }

    //Start a webserver for comms..
    //        mServer = new webserver(this);
    //        mServer.start();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    //Get a wake lock
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TermDebug.LOG_TAG);
    mScreenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TermDebug.LOG_TAG);
    mWifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, TermDebug.LOG_TAG);

    //Get the Initial Values
    //        boolean cpulock     = getStringPref("cpulock","1") == 1 ? true : false;
    //        boolean wifilock    = getStringPref("wifilock","0") == 1 ? true : false;
    //        boolean screenlock  = getStringPref("screenlock","0") == 1 ? true : false;
    setupWakeLocks();

    Log.d(TermDebug.LOG_TAG, "TermService started");

    return;
}