List of usage examples for android.app PendingIntent getService
public static PendingIntent getService(Context context, int requestCode, @NonNull Intent intent, @Flags int flags)
From source file:com.battlelancer.seriesguide.service.NotificationService.java
private void onNotify(final Cursor upcomingEpisodes, List<Integer> notifyPositions, long latestAirtime) { final Context context = getApplicationContext(); CharSequence tickerText;/*from w w w. ja v a2 s . c om*/ CharSequence contentTitle; CharSequence contentText; PendingIntent contentIntent; // base intent for task stack final Intent showsIntent = new Intent(context, ShowsActivity.class); showsIntent.putExtra(ShowsActivity.InitBundle.SELECTED_TAB, ShowsActivity.InitBundle.INDEX_TAB_UPCOMING); final int count = notifyPositions.size(); if (count == 1) { // notify in detail about one episode Timber.d("Notifying about 1 new episode"); upcomingEpisodes.moveToPosition(notifyPositions.get(0)); final String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE); tickerText = getString(R.string.upcoming_show, showTitle); contentTitle = showTitle + " " + Utils.getEpisodeNumber(this, upcomingEpisodes.getInt(NotificationQuery.SEASON), upcomingEpisodes.getInt(NotificationQuery.NUMBER)); // "8:00 PM on Network" final String releaseTime = TimeTools.formatToLocalReleaseTime(this, TimeTools.getEpisodeReleaseTime( this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS))); final String network = upcomingEpisodes.getString(NotificationQuery.NETWORK); contentText = getString(R.string.upcoming_show_detailed, releaseTime, network); Intent episodeDetailsIntent = new Intent(context, EpisodesActivity.class); episodeDetailsIntent.putExtra(EpisodesActivity.InitBundle.EPISODE_TVDBID, upcomingEpisodes.getInt(NotificationQuery._ID)); episodeDetailsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime); contentIntent = TaskStackBuilder.create(context).addNextIntent(showsIntent) .addNextIntent(episodeDetailsIntent) .getPendingIntent(REQUEST_CODE_SINGLE_EPISODE, PendingIntent.FLAG_CANCEL_CURRENT); } else { // notify about multiple episodes Timber.d("Notifying about " + count + " new episodes"); tickerText = getString(R.string.upcoming_episodes); contentTitle = getString(R.string.upcoming_episodes_number, count); contentText = getString(R.string.upcoming_display); contentIntent = TaskStackBuilder.create(context) .addNextIntent(showsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime)) .getPendingIntent(REQUEST_CODE_MULTIPLE_EPISODES, PendingIntent.FLAG_CANCEL_CURRENT); } final NotificationCompat.Builder nb = new NotificationCompat.Builder(context); if (AndroidUtils.isJellyBeanOrHigher()) { Timber.d("Building rich notification (JB+)"); // JELLY BEAN and above if (count == 1) { // single episode upcomingEpisodes.moveToPosition(notifyPositions.get(0)); maybeSetPoster(context, nb, upcomingEpisodes.getString(NotificationQuery.POSTER)); final String episodeTitle = upcomingEpisodes.getString(NotificationQuery.TITLE); final String episodeSummary = upcomingEpisodes.getString(NotificationQuery.OVERVIEW); final SpannableStringBuilder bigText = new SpannableStringBuilder(); bigText.append(TextUtils.isEmpty(episodeTitle) ? "" : episodeTitle); bigText.setSpan(new StyleSpan(Typeface.BOLD), 0, bigText.length(), 0); bigText.append("\n"); bigText.append(TextUtils.isEmpty(episodeSummary) ? "" : episodeSummary); nb.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(contentText)); // Action button to check in Intent checkInActionIntent = new Intent(context, QuickCheckInActivity.class); checkInActionIntent.putExtra(QuickCheckInActivity.InitBundle.EPISODE_TVDBID, upcomingEpisodes.getInt(NotificationQuery._ID)); checkInActionIntent .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); PendingIntent checkInIntent = PendingIntent.getActivity(context, REQUEST_CODE_ACTION_CHECKIN, checkInActionIntent, PendingIntent.FLAG_CANCEL_CURRENT); nb.addAction(R.drawable.ic_action_checkin, getString(R.string.checkin), checkInIntent); } else { // multiple episodes NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); // display at most the first five for (int displayIndex = 0; displayIndex < Math.min(count, 5); displayIndex++) { if (!upcomingEpisodes.moveToPosition(notifyPositions.get(displayIndex))) { // could not go to the desired position (testing just in case) break; } final SpannableStringBuilder lineText = new SpannableStringBuilder(); // show title String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE); lineText.append(TextUtils.isEmpty(showTitle) ? "" : showTitle); lineText.setSpan(new StyleSpan(Typeface.BOLD), 0, lineText.length(), 0); lineText.append(" "); // "8:00 PM on Network" String releaseTime = TimeTools.formatToLocalReleaseTime(this, TimeTools.getEpisodeReleaseTime( this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS))); String network = upcomingEpisodes.getString(NotificationQuery.NETWORK); lineText.append(getString(R.string.upcoming_show_detailed, releaseTime, network)); inboxStyle.addLine(lineText); } // tell if we could not display all episodes if (count > 5) { inboxStyle.setSummaryText(getString(R.string.more, count - 5)); } nb.setStyle(inboxStyle); nb.setContentInfo(String.valueOf(count)); } } else { // ICS and below if (count == 1) { // single episode upcomingEpisodes.moveToPosition(notifyPositions.get(0)); maybeSetPoster(context, nb, upcomingEpisodes.getString(NotificationQuery.POSTER)); } } // notification sound final String ringtoneUri = NotificationSettings.getNotificationsRingtone(context); // If the string is empty, the user chose silent... if (ringtoneUri.length() != 0) { // ...otherwise set the specified ringtone Timber.d("Notification has sound"); nb.setSound(Uri.parse(ringtoneUri)); } // vibration if (NotificationSettings.isNotificationVibrating(context)) { Timber.d("Notification vibrates"); nb.setVibrate(VIBRATION_PATTERN); } nb.setDefaults(Notification.DEFAULT_LIGHTS); nb.setWhen(System.currentTimeMillis()); nb.setAutoCancel(true); nb.setTicker(tickerText); nb.setContentTitle(contentTitle); nb.setContentText(contentText); nb.setContentIntent(contentIntent); nb.setSmallIcon(R.drawable.ic_notification); nb.setColor(getResources().getColor(R.color.accent_primary)); nb.setPriority(NotificationCompat.PRIORITY_DEFAULT); nb.setCategory(NotificationCompat.CATEGORY_EVENT); Timber.d("Setting delete intent with episode time: " + latestAirtime); Intent i = new Intent(this, NotificationService.class); i.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime); PendingIntent deleteIntent = PendingIntent.getService(this, REQUEST_CODE_DELETE_INTENT, i, PendingIntent.FLAG_CANCEL_CURRENT); nb.setDeleteIntent(deleteIntent); // build the notification Notification notification = nb.build(); // use string resource id, always unique within app final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(R.string.upcoming_show, notification); }
From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java
void startRecurringBootAlarm() { if (recurringBootIntent != null) { alarmManager.cancel(recurringBootIntent); //return; }// www . j a va 2 s . c o m recurringBootIntent = null; GregorianCalendar gToday = new GregorianCalendar( TimeZone.getTimeZone(getResources().getString(R.string.my_time_zone_en))); if (gToday.get(Calendar.HOUR_OF_DAY) >= 7 && gToday.get(Calendar.HOUR_OF_DAY) < 19) return; String bootParameter = readBootParameter(99); Log.i("ALARM_SET", "got n boot parameters " + (bootParameter == null ? "nothing" : bootParameter)); if (bootParameter == null) return; int idx = bootParameter.indexOf("-"); if (idx < 0) return; long init_wait = Long.parseLong(bootParameter.substring(0, idx)); if (init_wait < 2000) //init_wait=2000; { int ixx = bootParameter.indexOf("-", idx + 1); long on_time = Long.parseLong(bootParameter.substring(idx + 1, ixx)); sendCommand("M5-" + new DecimalFormat("00").format(on_time / 60000)); long off_time = Long.parseLong(bootParameter.substring(ixx + 1)); setRecurringBootAlarm(on_time, off_time); return; } Intent jIntent = new Intent(this, ConnectDaemonService.class); //M1-00 (cool) or M1-01 (warm) jIntent.setAction(ALARM_NBOOT); jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_NBOOT); jIntent.putExtra(ConnectDaemonService.ALARM_NBOOT, bootParameter.substring(idx + 1)); recurringBootIntent = PendingIntent.getService(this, ++nBootAlarmRequestId % 100 + 200, jIntent, PendingIntent.FLAG_ONE_SHOT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + init_wait, recurringBootIntent); //alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + init_wait, //on_time + off_time, recurringBootIntent); //Log.i("ALARM_SET", "to start recurring boot in " + init_wait/60000);//+" with interval "+(on_time+off_time)/60000); Log.i("ALARM_SET", "to start recurring boot in " + init_wait / 60000); //startScheduledJobs(); }
From source file:com.andrew.apollo.MusicPlaybackService.java
private void initService() { // Initialize the favorites and recents databases mFavoritesCache = FavoritesStore.getInstance(this); mRecentsCache = RecentStore.getInstance(this); // Initialize the notification helper mNotificationHelper = new NotificationHelper(this); // Initialize the image fetcher mImageFetcher = ImageFetcher.getInstance(this); // Initialize the image cache mImageFetcher.setImageCache(ImageCache.getInstance(this)); // Start up the thread running the service. Note that we create a // separate thread because the service normally runs in the process's // main thread, which we don't want to block. We also make it // background priority so CPU-intensive work will not disrupt the UI. final HandlerThread thread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND); thread.start();/*from w ww . j a v a 2 s . c o m*/ // Initialize the handler mPlayerHandler = new MusicPlayerHandler(this, thread.getLooper()); // Initialize the audio manager and register any headset controls for // playback mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mMediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()); try { if (mAudioManager != null) { mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent); } } catch (SecurityException e) { e.printStackTrace(); // ignore // some times the phone does not grant the MODIFY_PHONE_STATE permission // this permission is for OMEs and we can't do anything about it } // Use the remote control APIs to set the playback state setUpRemoteControlClient(); // Initialize the preferences mPreferences = getSharedPreferences("Service", 0); mCardId = getCardId(); registerExternalStorageListener(); // Initialize the media player mPlayer = new MultiPlayer(this); mPlayer.setHandler(mPlayerHandler); ConfigurationManager CM = ConfigurationManager.instance(); // Load Repeat Mode setRepeatMode(CM.getInt(Constants.PREF_KEY_GUI_PLAYER_REPEAT_MODE)); // Load Shuffle Mode On/Off enableShuffle(CM.getBoolean(Constants.PREF_KEY_GUI_PLAYER_SHUFFLE_ENABLED)); MusicUtils.isShuffleEnabled(); // Initialize the intent filter and each action final IntentFilter filter = new IntentFilter(); filter.addAction(SERVICECMD); filter.addAction(TOGGLEPAUSE_ACTION); filter.addAction(PAUSE_ACTION); filter.addAction(STOP_ACTION); filter.addAction(NEXT_ACTION); filter.addAction(PREVIOUS_ACTION); filter.addAction(REPEAT_ACTION); filter.addAction(SHUFFLE_ACTION); // Attach the broadcast listener registerReceiver(mIntentReceiver, filter); // Initialize the wake lock final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); if (powerManager != null) { mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); mWakeLock.setReferenceCounted(false); } // Initialize the delayed shutdown intent final Intent shutdownIntent = new Intent(this, MusicPlaybackService.class); shutdownIntent.setAction(SHUTDOWN_ACTION); mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0); // Listen for the idle state scheduleDelayedShutdown(); // Bring the queue back reloadQueue(); notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); updateNotification(); }
From source file:com.t2.compassionMeditation.Graphs1Activity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()"); // We don't want the screen to timeout in this activity getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView setContentView(R.layout.graphs_activity_layout); mInstance = this; sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true); mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false); mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false); mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false); if (mAntHrmEnabled) { mHeartRateSource = HEARTRATE_ANT; } else {//from ww w. ja v a 2 s .c o m mHeartRateSource = HEARTRATE_ZEPHYR; } // The session start time will be used as session id // Note this also sets session start time // **** This session ID will be prepended to all JSON data stored // in the external database until it's changed (by the start // of a new session. Calendar cal = Calendar.getInstance(); SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US); String sessionDate = sdf.format(new Date()); String userId = SharedPref.getString(this, "SelectedUser", ""); long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0); mDataOutHandler = new DataOutHandler(this, userId, sessionDate, mAppId, DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId); if (mDatabaseEnabled) { TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); String myNumber = telephonyManager.getLine1Number(); String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name", getString(R.string.database_uri)); // remoteDatabaseUri += myNumber; Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove try { mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName, remoteDatabaseUri); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } mDataOutHandler.setRequiresAuthentication(false); } mBioDataProcessor.initialize(mDataOutHandler); if (mLoggingEnabled) { mDataOutHandler.enableLogging(this); } if (mLogCatEnabled) { mDataOutHandler.enableLogCat(); } // Log the version try { PackageManager packageManager = getPackageManager(); PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0); mApplicationVersion = info.versionName; String versionString = mAppId + " application version: " + mApplicationVersion; DataOutPacket packet = new DataOutPacket(); packet.add(DataOutHandlerTags.version, versionString); try { mDataOutHandler.handleDataOut(packet); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } } catch (NameNotFoundException e) { Log.e(TAG, e.toString()); } // Set up UI elements Resources resources = this.getResources(); AssetManager assetManager = resources.getAssets(); mPauseButton = (Button) findViewById(R.id.buttonPause); mAddMeasureButton = (Button) findViewById(R.id.buttonAddMeasure); mTextInfoView = (TextView) findViewById(R.id.textViewInfo); mMeasuresDisplayText = (TextView) findViewById(R.id.measuresDisplayText); // Don't actually show skin conductance meter unless we get samples ImageView image = (ImageView) findViewById(R.id.imageView1); image.setImageResource(R.drawable.signal_bars0); // Check to see of there a device configured for EEG, if so then show the skin conductance meter String tmp = SharedPref.getString(this, "EEG", null); if (tmp != null) { image.setVisibility(View.VISIBLE); } else { image.setVisibility(View.INVISIBLE); } // Initialize SPINE by passing the fileName with the configuration properties try { mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources); } catch (InstantiationException e) { Log.e(TAG, "Exception creating SPINE manager: " + e.toString()); e.printStackTrace(); } try { currentMindsetData = new MindsetData(this); } catch (Exception e1) { Log.e(TAG, "Exception creating MindsetData: " + e1.toString()); e1.printStackTrace(); } // Establish nodes for BSPAN // Create a broadcast receiver. Note that this is used ONLY for command messages from the service // All data from the service goes through the mail SPINE mechanism (received(Data data)). // See public void received(Data data) this.mCommandReceiver = new SpineReceiver(this); int itemId = 0; eegPos = itemId; // eeg always comes first mBioParameters.clear(); // First create GraphBioParameters for each of the EEG static params (ie mindset) for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true); param.isShimmer = false; mBioParameters.add(param); } // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, EEG, HR, Skin Temp, Resp Rate // String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names); String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names_less_eeg); for (String paramName : paramNamesStringArray) { if (paramName.equalsIgnoreCase("not assigned")) continue; GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true); if (paramName.equalsIgnoreCase("gsr")) { gsrPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("emg")) { emgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("ecg")) { ecgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("heart rate")) { heartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("resp rate")) { respRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("skin temp")) { skinTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Airflow")) { eHealthAirFlowPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Temp")) { eHealthTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth SpO2")) { eHealthSpO2Pos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Heartrate")) { eHealthHeartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth GSR")) { eHealthGSRPos = itemId; param.isShimmer = false; } itemId++; mBioParameters.add(param); } // Since These are static nodes (Non-spine) we have to manually put them in the active node list Node mindsetNode = null; mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET)); // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor mManager.getActiveNodes().add(mindsetNode); Node zepherNode = null; zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR)); mManager.getActiveNodes().add(zepherNode); // The arduino node is programmed to look like a static Spine node // Note that currently we don't have to turn it on or off - it's always streaming // Since Spine (in this case) is a static node we have to manually put it in the active node list // Since the final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001 mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE)); mManager.getActiveNodes().add(mSpineNode); final String sessionName; // Check to see if we were requested to play back a previous session try { Bundle bundle = getIntent().getExtras(); if (bundle != null) { sessionName = bundle.getString(BioZenConstants.EXTRA_SESSION_NAME); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Replay Session " + sessionName + "?"); alert.setMessage("Make sure to turn off all Bluetooth Sensors!"); alert.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { mDataOutHandler.logNote("Replaying data from session " + sessionName); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } replaySessionData(sessionName); AlertDialog.Builder alert1 = new AlertDialog.Builder(mInstance); alert1.setTitle("INFO"); alert1.setMessage("Replay of session complete!"); alert1.show(); } }); alert.show(); } } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); } if (mInternalSensorMonitoring) { // IntentSender Launches our service scheduled with with the alarm manager mBigBrotherService = PendingIntent.getService(Graphs1Activity.this, 0, new Intent(Graphs1Activity.this, BigBrotherService.class), 0); long firstTime = SystemClock.elapsedRealtime(); // Schedule the alarm! AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000, mBigBrotherService); // Tell the user about what we did. Toast.makeText(Graphs1Activity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show(); } //testFIRFilter(); // testHR(); }
From source file:com.google.android.gms.location.sample.geofencing.MainActivity.java
/** * Gets a PendingIntent to send with the request to add or remove Geofences. Location Services * issues the Intent inside this PendingIntent whenever a geofence transition occurs for the * current list of geofences.//from w ww. j av a 2s. c om * * @return A PendingIntent for the IntentService that handles geofence transitions. */ private PendingIntent getGeofencePendingIntent() { // Reuse the PendingIntent if we already have it. if (mGeofencePendingIntent != null) { return mGeofencePendingIntent; } Intent intent = new Intent(this, GeofenceTransitionsIntentService.class); // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling // addGeofences() and removeGeofences(). return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); }
From source file:com.androidinspain.deskclock.data.TimerModel.java
/** * Updates the callback given to this application from the {@link AlarmManager} that signals the * expiration of the next timer. If no timers are currently set to expire (i.e. no running * timers exist) then this method clears the expiration callback from AlarmManager. *//*from w w w . j a v a2 s . co m*/ private void updateAlarmManager() { // Locate the next firing timer if one exists. Timer nextExpiringTimer = null; for (Timer timer : getMutableTimers()) { if (timer.isRunning()) { if (nextExpiringTimer == null) { nextExpiringTimer = timer; } else if (timer.getExpirationTime() < nextExpiringTimer.getExpirationTime()) { nextExpiringTimer = timer; } } } // Build the intent that signals the timer expiration. final Intent intent = TimerService.createTimerExpiredIntent(mContext, nextExpiringTimer); if (nextExpiringTimer == null) { // Cancel the existing timer expiration callback. final PendingIntent pi = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE); if (pi != null) { mAlarmManager.cancel(pi); pi.cancel(); } } else { // Update the existing timer expiration callback. final PendingIntent pi = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); schedulePendingIntent(mAlarmManager, nextExpiringTimer.getExpirationTime(), pi); } }
From source file:com.example.cody.tapwater.activities.MainActivity.java
@Override public void onResume() { super.onResume(); System.out.println("Alarm manager setup"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); String prompts = prefs.getString("prompts", "5"); String beginStr = prefs.getString("begin_time", ""); String endStr = prefs.getString("end_time", ""); Calendar beginCal = Calendar.getInstance(); Calendar endCal = Calendar.getInstance(); try {//from w w w . j a va 2 s.c om beginCal.setTime(sdf.parse(beginStr)); endCal.setTime(sdf.parse(endStr)); } catch (ParseException e) { e.printStackTrace(); } long interval = notificationIntervalCalculation(Integer.valueOf(prompts), beginCal, endCal); AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Intent i = new Intent(context, NotificationService.class); PendingIntent pi = PendingIntent.getService(context, 0, i, 0); am.cancel(pi); // by my own convention, minutes <= 0 means notifications are disabled if (interval > 0) { am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval, interval, pi); } }
From source file:com.aware.Aware.java
/** * Starts a plugin. Expects the package name of the plugin.<br/> * It checks if the plugin does exist on the phone. If it doesn't, it will request the user to install it automatically. * @param context/*from w ww.j a v a2 s. c o m*/ * @param package_name */ public static void startPlugin(Context context, String package_name) { //Check if plugin is installed. If not, ask user to download it. Cursor is_installed = context.getContentResolver().query(Aware_Plugins.CONTENT_URI, null, Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null, null); if (is_installed != null && is_installed.moveToFirst()) { //We might just have it cached, but not installed if (isClassAvailable(context, package_name, "Plugin")) { //it's installed, start it! Intent plugin = new Intent(); plugin.setClassName(package_name, package_name + ".Plugin"); context.startService(plugin); if (Aware.DEBUG) Log.d(TAG, package_name + " started..."); ContentValues rowData = new ContentValues(); rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_ON); context.getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData, Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null); is_installed.close(); return; } is_installed.close(); } HttpResponse response = new Https(awareContext) .dataGET("https://api.awareframework.com/index.php/plugins/get_plugin/" + package_name); if (response != null && response.getStatusLine().getStatusCode() == 200) { try { String data = EntityUtils.toString(response.getEntity()); if (data.equals("[]")) return; JSONObject json_package = new JSONObject(data); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); mBuilder.setSmallIcon(R.drawable.ic_stat_aware_plugin_dependency); mBuilder.setContentTitle("AWARE"); mBuilder.setContentText("Plugin missing: " + json_package.getString("title") + ". Tap to install."); mBuilder.setDefaults(Notification.DEFAULT_ALL); mBuilder.setAutoCancel(true); Intent pluginIntent = new Intent(context, DownloadPluginService.class); pluginIntent.putExtra("package_name", package_name); pluginIntent.putExtra("is_update", false); PendingIntent clickIntent = PendingIntent.getService(context, 0, pluginIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(clickIntent); NotificationManager notManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); notManager.notify(json_package.getInt("id"), mBuilder.build()); } catch (ParseException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.vuze.android.remote.service.VuzeService.java
private NotificationCompat.Builder getNotificationBuilder() { Resources resources = getResources(); final Intent notificationIntent = new Intent(this, IntentHandler.class); final PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0); String title = resources.getString(R.string.core_noti_title); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_small).setContentTitle(title).setOngoing(true) .setCategory(Notification.CATEGORY_SERVICE).setContentIntent(pi); if (!isCoreStopping) { Intent intentStop = new Intent(this, VuzeService.class); intentStop.setAction(INTENT_ACTION_STOP); PendingIntent piStop = PendingIntent.getService(this, 0, intentStop, PendingIntent.FLAG_CANCEL_CURRENT); builder.addAction(R.drawable.ic_power_settings_new_white_24dp, resources.getString(R.string.core_noti_stop_button), piStop); AzureusCore core = getCore();/*from w w w. j ava 2 s .c o m*/ if (core != null && core.isStarted()) { GlobalManager gm = core.getGlobalManager(); if (gm != null) { boolean canPause = gm.canPauseDownloads(); Intent intentPR = new Intent(this, VuzeService.class); intentPR.setAction(canPause ? INTENT_ACTION_PAUSE : INTENT_ACTION_RESUME); PendingIntent piPR = PendingIntent.getService(this, 0, intentPR, PendingIntent.FLAG_CANCEL_CURRENT); builder.addAction( canPause ? R.drawable.ic_playlist_pause_n : R.drawable.ic_playlist_play_white_n, resources.getString( canPause ? R.string.core_noti_pause_button : R.string.core_noti_resume_button), piPR); } } } String subTitle = null; if (isCoreStopping || isServiceStopping) { int id = restartService ? R.string.core_noti_restarting : R.string.core_noti_stopping; subTitle = resources.getString(id); } else { if (bindToLocalHost) { subTitle = resources.getString(bindToLocalHostReasonID); } else { GlobalManagerStats stats = null; AzureusCore core = getCore(); if (core != null && core.isStarted()) { GlobalManager gm = staticCore.getGlobalManager(); if (gm != null) { stats = gm.getStats(); } } if (stats != null) { String downSpeed = DisplayFormatters .formatByteCountToKiBEtcPerSec(stats.getDataAndProtocolSendRate()); String upSpeed = DisplayFormatters .formatByteCountToKiBEtcPerSec(stats.getDataAndProtocolReceiveRate()); TagManager tagManager = TagManagerFactory.getTagManager(); Tag tagActive = tagManager.lookupTagByUID(7);// active int numActive = tagActive == null ? 0 : tagActive.getTaggedCount(); subTitle = resources.getQuantityString(R.plurals.core_noti_running, numActive, downSpeed, upSpeed, DisplayFormatters.formatNumber(numActive)); } else { subTitle = resources.getString(R.string.core_noti_starting); } } } builder.setContentText(subTitle); return builder; }
From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java
void setRecurringBootAlarm(long on_time, long idle_interval) { if (recurringBootIntent != null) { alarmManager.cancel(recurringBootIntent); //return; }// w w w .java 2s . c om recurringBootIntent = null; GregorianCalendar gToday = new GregorianCalendar( TimeZone.getTimeZone(getResources().getString(R.string.my_time_zone_en))); if (gToday.get(Calendar.HOUR_OF_DAY) >= 7 && gToday.get(Calendar.HOUR_OF_DAY) < 21) return; long total_wait = idle_interval;//on_time+idle_interval; String bootParameter = "" + on_time + "-" + idle_interval; Intent jIntent = new Intent(this, ConnectDaemonService.class); //M1-00 (cool) or M1-01 (warm) jIntent.setAction(ALARM_NBOOT); jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_NBOOT); jIntent.putExtra(ConnectDaemonService.ALARM_NBOOT, bootParameter); recurringBootIntent = PendingIntent.getService(this, ++nBootAlarmRequestId % 100 + 300, jIntent, PendingIntent.FLAG_ONE_SHOT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + total_wait, recurringBootIntent); Log.i("ALARM_SET", "to start recurring boot in " + total_wait / 60000); //startScheduledJobs(); }