List of usage examples for android.app PendingIntent getBroadcast
public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, @Flags int flags)
From source file:com.google.android.libraries.cast.companionlibrary.notification.VideoCastNotificationService.java
/** * Returns the {@link NotificationCompat.Action} for disconnecting this app from the cast * device./* w ww .ja va2s. c o m*/ */ protected NotificationCompat.Action getDisconnectAction() { Intent intent = new Intent(ACTION_STOP); intent.setPackage(getPackageName()); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); return new NotificationCompat.Action.Builder(R.drawable.ic_notification_disconnect_24dp, getString(R.string.ccl_disconnect), pendingIntent).build(); }
From source file:com.mobilyzer.MeasurementScheduler.java
private synchronized void handleMeasurement() { alarmManager.cancel(measurementIntentSender); setCurrentTask(null);// w ww . j a v a 2 s .c o m try { Logger.d("MeasurementScheduler -> In handleMeasurement " + mainQueue.size() + " " + waitingTasksQueue.size()); MeasurementTask task = mainQueue.peek(); // update the waiting queue. It contains all the tasks that are ready // to be executed. Here we extract all those ready tasks from main queue while (task != null && task.timeFromExecution() <= 0) { mainQueue.poll(); if (task.getDescription().getType().equals(RRCTask.TYPE) && phoneUtils.getNetwork().equals(PhoneUtils.NETWORK_WIFI)) { long updatedStartTime = System.currentTimeMillis() + (long) (10 * 60 * 1000); task.getDescription().startTime.setTime(updatedStartTime); mainQueue.add(task); Logger.i("MeasurementScheduler: handleMeasurement: delaying RRC task on " + phoneUtils.getNetwork()); task = mainQueue.peek(); continue; } Logger.i("MeasurementScheduler: handleMeasurement: " + task.getDescription().key + " " + task.getDescription().type + " added to waiting list"); waitingTasksQueue.add(task); task = mainQueue.peek(); } if (!phoneUtils.isNetworkAvailable()) { Logger.i("No connection is available, set an alarm for 5 min"); measurementIntentSender = PendingIntent.getBroadcast(this, 0, new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 60 * 1000), measurementIntentSender); return; } if (waitingTasksQueue.size() != 0) { Logger.i("waiting list size is " + waitingTasksQueue.size()); MeasurementTask ready = waitingTasksQueue.poll(); Logger.i("ready: " + ready.getDescription().getType()); MeasurementDesc desc = ready.getDescription(); long newStartTime = desc.startTime.getTime() + (long) desc.intervalSec * 1000; if (desc.count == MeasurementTask.INFINITE_COUNT && desc.priority != MeasurementTask.USER_PRIORITY) { if (serverTasks.containsKey(desc.toString()) && serverTasks.get(desc.toString()).after(desc.endTime)) { ready.getDescription().endTime.setTime(serverTasks.get(desc.toString()).getTime()); } } /** * Add a clone of the task if it's still valid it does not change the taskID (hashCode) */ if (newStartTime < ready.getDescription().endTime.getTime() && (desc.count == MeasurementTask.INFINITE_COUNT || desc.count > 1)) { MeasurementTask newTask = ready.clone(); if (desc.count != MeasurementTask.INFINITE_COUNT) { newTask.getDescription().count--; } newTask.getDescription().startTime.setTime(newStartTime); tasksStatus.put(newTask.getTaskId(), TaskStatus.SCHEDULED); mainQueue.add(newTask); } else { if (desc.priority != MeasurementTask.USER_PRIORITY) { serverTasks.remove(desc.toString()); } } if (ready.getDescription().endTime.before(new Date())) { Intent intent = new Intent(); intent.setAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION); intent.putExtra(UpdateIntent.TASK_STATUS_PAYLOAD, Config.TASK_CANCELED); MeasurementResult[] tempResults = MeasurementResult.getFailureResult(ready, new CancellationException("Task cancelled!")); intent.putExtra(UpdateIntent.RESULT_PAYLOAD, tempResults); intent.putExtra(UpdateIntent.TASKID_PAYLOAD, ready.getTaskId()); intent.putExtra(UpdateIntent.CLIENTKEY_PAYLOAD, ready.getKey()); MeasurementScheduler.this.sendBroadcast(intent); if (desc.priority != MeasurementTask.USER_PRIORITY) { serverTasks.remove(desc.toString()); } handleMeasurement(); } else { Logger.d("MeasurementScheduler -> " + ready.getDescription().getType() + " is gonna run"); Future<MeasurementResult[]> future; setCurrentTask(ready); setCurrentTaskStartTime(Calendar.getInstance().getTime()); if (ready.getDescription().priority == MeasurementTask.USER_PRIORITY) { // User task can override the power policy. So a different task wrapper is used. future = measurementExecutor.submit(new UserMeasurementTask(ready, this)); } else { future = measurementExecutor .submit(new ServerMeasurementTask(ready, this, resourceCapManager)); } synchronized (pendingTasks) { pendingTasks.put(ready, future); } } } else {// if(task.timeFromExecution()>0){ MeasurementTask waiting = mainQueue.peek(); if (waiting != null) { long timeFromExecution = task.timeFromExecution(); measurementIntentSender = PendingIntent.getBroadcast(this, 0, new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution, measurementIntentSender); setCurrentTask(null);// TODO setCurrentTaskStartTime(null); } } } catch (IllegalArgumentException e) { // Task creation in clone can create this exception } catch (Exception e) { // We don't want any unexpected exception to crash the process } }
From source file:arun.com.chromer.browsing.customtabs.CustomTabs.java
/** * Adds an open in chrome option/*from ww w . j a v a 2 s . c o m*/ */ private void prepareOpenInChrome() { final String customTabPkg = Preferences.get(activity).customTabPackage(); if (Utils.isPackageInstalled(activity, customTabPkg)) { if (customTabPkg.equalsIgnoreCase(BETA_PACKAGE) || customTabPkg.equalsIgnoreCase(DEV_PACKAGE) || customTabPkg.equalsIgnoreCase(STABLE_PACKAGE)) { final Intent chromeReceiver = new Intent(activity, OpenInChromeReceiver.class); final PendingIntent openChromePending = PendingIntent.getBroadcast(activity, 0, chromeReceiver, FLAG_UPDATE_CURRENT); final String app = Utils.getAppNameWithPackage(activity, customTabPkg); final String label = String.format(activity.getString(R.string.open_in_browser), app); builder.addMenuItem(label, openChromePending); } } }
From source file:com.olearyp.gusto.Expsetup.java
protected void sendCommand(final String command, final String description, final String state) { final Intent runCmd = new Intent("com.olearyp.gusto.SUEXEC"); runCmd.setData(//from w w w. j ava 2 s .c o m Uri.fromParts("command", ". /system/bin/exp_script.sh.lib && read_in_ep_config && " + command, "")) .putExtra("com.olearyp.gusto.STATE", state); final Notification note = new Notification(R.drawable.icon, description.substring(0, 1).toUpperCase() + description.substring(1) + "...", System.currentTimeMillis()); note.setLatestEventInfo(Expsetup.this, getString(R.string.app_name), getString(R.string.app_name) + " is " + description + "...", PendingIntent.getBroadcast(Expsetup.this, 0, null, 0)); runCmd.putExtra("com.olearyp.gusto.RUN_NOTIFICATION", note); startService(runCmd); setServerState(state); if (getServerState().equals(getString(R.string.reboot_manual_flash_required))) { final Intent intent = new Intent("com.olearyp.gusto.SUEXEC") .setData(Uri.fromParts("commandid", Integer.toString(R.string.reboot_recovery), "")); final PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0); final Notification rebootNote = new Notification(R.drawable.status_reboot, getString(R.string.reboot_recovery_required_msg), System.currentTimeMillis()); rebootNote.setLatestEventInfo(this, "GUSTO reboot request", getString(R.string.reboot_recovery_doit_msg), contentIntent); rebootNote.deleteIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.olearyp.gusto.RESET_SERVER_STATE"), 0); rebootNote.flags |= Notification.FLAG_SHOW_LIGHTS; rebootNote.ledOnMS = 200; rebootNote.ledOffMS = 400; rebootNote.ledARGB = Color.argb(255, 255, 0, 0); nm.notify(REBOOT_NOTIFICATION, rebootNote); } else if (getServerState().equals(getString(R.string.reboot_recovery_required))) { final Intent intent = new Intent("com.olearyp.gusto.SUEXEC") .setData(Uri.fromParts("commandid", Integer.toString(R.string.reboot), "")); final PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0); final Notification rebootNote = new Notification(R.drawable.status_reboot, getString(R.string.reboot_autoflash_required_msg), System.currentTimeMillis()); rebootNote.setLatestEventInfo(this, "GUSTO reboot request", getString(R.string.reboot_autoflash_doit_msg), contentIntent); rebootNote.deleteIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.olearyp.gusto.RESET_SERVER_STATE"), 0); rebootNote.flags |= Notification.FLAG_SHOW_LIGHTS; rebootNote.ledOnMS = 200; rebootNote.ledOffMS = 600; rebootNote.ledARGB = Color.argb(255, 255, 255, 0); nm.notify(REBOOT_NOTIFICATION, rebootNote); } else if (getServerState().equals(getString(R.string.reboot_required))) { final Intent intent = new Intent("com.olearyp.gusto.SUEXEC") .setData(Uri.fromParts("commandid", Integer.toString(R.string.reboot), "")); final PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0); final Notification rebootNote = new Notification(R.drawable.status_reboot, getString(R.string.reboot_required_msg), System.currentTimeMillis()); rebootNote.setLatestEventInfo(this, "GUSTO reboot request", getString(R.string.reboot_doit_msg), contentIntent); rebootNote.deleteIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.olearyp.gusto.RESET_SERVER_STATE"), 0); rebootNote.flags |= Notification.FLAG_SHOW_LIGHTS; rebootNote.ledOnMS = 200; rebootNote.ledOffMS = 600; rebootNote.ledARGB = Color.argb(255, 255, 255, 0); nm.notify(REBOOT_NOTIFICATION, rebootNote); } }
From source file:cw.kop.autobackground.sources.SourceListFragment.java
/** * Starts (or stops) download and sets download icon appropriately */// www .j a va 2 s . c o m private void startDownload() { listAdapter.saveData(); if (FileHandler.isDownloading) { DialogFactory.ActionDialogListener listener = new DialogFactory.ActionDialogListener() { @Override public void onClickRight(View v) { FileHandler.cancel(appContext); resetActionBarDownload(); dismissDialog(); } }; DialogFactory.showActionDialog(appContext, "", "Cancel download?", listener, -1, R.string.cancel_button, R.string.ok_button); } else if (FileHandler.download(appContext)) { Drawable drawable = getResources().getDrawable(R.drawable.ic_cancel_white_24dp); drawable.setColorFilter(AppSettings.getColorFilterInt(appContext), PorterDuff.Mode.MULTIPLY); toolbarMenu.getItem(1).setIcon(drawable); if (AppSettings.resetOnManualDownload() && AppSettings.useTimer() && AppSettings.getTimerDuration() > 0) { Intent intent = new Intent(); intent.setAction(LiveWallpaperService.DOWNLOAD_WALLPAPER); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); PendingIntent pendingIntent = PendingIntent.getBroadcast(appContext, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pendingIntent); alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis() + AppSettings.getTimerDuration(), AppSettings.getTimerDuration(), pendingIntent); } } }
From source file:com.etime.ETimeActivity.java
/** * Set the alarm that will perform autoclock out at the specified time. * @param alarmTime time in milliseconds since epoch when the alarm * should run.// w w w . ja va2s. c o m */ public void setOneTimeAlarm(long alarmTime) { Intent intent = new Intent(this, TimeAlarm.class); intent.putExtra("username", loginName); intent.putExtra("password", password); pendingIntentAutoClockAlarm = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); am.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntentAutoClockAlarm); }
From source file:com.daskiworks.ghwatch.backend.UnreadNotificationsService.java
protected void fireAndroidNotification(NotificationStream newStream, NotificationStream oldStream) { if (newStream == null || !PreferencesUtils.getBoolean(context, PreferencesUtils.PREF_NOTIFY, true)) return;/*from ww w .j a va 2s . c om*/ Log.d(TAG, "fireAndroidNotification count before filter " + newStream.size()); newStream = filterForAndroidNotification(newStream); Log.d(TAG, "fireAndroidNotification count after filter " + newStream.size()); if (newStream.isNewNotification(oldStream)) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.github_notification) .setContentTitle(context.getString(R.string.an_title_more)) .setPriority(NotificationCompat.PRIORITY_DEFAULT); mBuilder.setAutoCancel(true); if (newStream.size() > 1) mBuilder.setNumber(newStream.size()); boolean allFromOne = newStream.allNotificationsFromSameRepository(); if (newStream.size() == 1 || allFromOne) { // only one repository Notification n = newStream.get(0); Bitmap b = ImageLoader.getInstance(context).loadImageWithFileLevelCache(n.getRepositoryAvatarUrl()); if (b != null) { mBuilder.setLargeIcon(b); } else { mBuilder.setLargeIcon( BitmapFactory.decodeResource(context.getResources(), R.drawable.github_notification)); } mBuilder.setContentText(n.getRepositoryFullName()); } else { mBuilder.setLargeIcon( BitmapFactory.decodeResource(context.getResources(), R.drawable.github_notification)); } Intent resultIntent = null; if (newStream.size() == 1) { mBuilder.setContentTitle(context.getString(R.string.an_title_one)); Notification n = newStream.get(0); mBuilder.setContentText(n.getRepositoryFullName() + ": " + n.getSubjectTitle()); NotificationCompat.BigTextStyle btStyle = new NotificationCompat.BigTextStyle(); btStyle.bigText(n.getSubjectTitle()); btStyle.setSummaryText(n.getRepositoryFullName()); mBuilder.setStyle(btStyle); Intent actionIntent = new Intent(context, MarkNotifiationAsReadReceiver.class); actionIntent.putExtra(MarkNotifiationAsReadReceiver.INTENT_EXTRA_KEY_ID, n.getId()); mBuilder.addAction(R.drawable.ic_action_dismis_all, context.getString(R.string.action_mark_read), PendingIntent.getBroadcast(context, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT)); resultIntent = new Intent(context, MainActivity.class); } else { NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); for (Notification n : newStream) { if (allFromOne) { inboxStyle.addLine(n.getSubjectTitle()); } else { inboxStyle.addLine(n.getRepositoryFullName() + ": " + n.getSubjectTitle()); } } if (allFromOne) inboxStyle.setSummaryText(newStream.get(0).getRepositoryFullName()); else inboxStyle.setSummaryText(" "); mBuilder.setStyle(inboxStyle); Intent actionIntent = new Intent(context, MainActivity.class); actionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); actionIntent.setAction(MainActivity.INTENT_ACTION_DISMISS_ALL); mBuilder.addAction(R.drawable.ic_action_dismis_all, context.getString(R.string.action_all_read), PendingIntent.getActivity(context, 0, actionIntent, 0)); resultIntent = new Intent(context, MainActivity.class); } resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); resultIntent.setAction(MainActivity.INTENT_ACTION_SHOW); PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0); mBuilder.setContentIntent(resultPendingIntent); String nsound = PreferencesUtils.getString(context, PreferencesUtils.PREF_NOTIFY_SOUND, null); Log.d(TAG, "Notification sound from preference: " + nsound); if (nsound != null) { mBuilder.setSound(Uri.parse(nsound)); } if (PreferencesUtils.getBoolean(context, PreferencesUtils.PREF_NOTIFY_VIBRATE, true)) { mBuilder.setVibrate(new long[] { 0, 300, 100, 150, 100, 150 }); } mBuilder.setLights(0xffffffff, 100, 4000); // mId allows you to update the notification later on. Utils.getNotificationManager(context).notify(ANDROID_NOTIFICATION_ID, mBuilder.build()); ActivityTracker.sendEvent(context, ActivityTracker.CAT_NOTIF, "new_notif", "notif count: " + newStream.size(), Long.valueOf(newStream.size())); } else if (newStream.isEmpty()) { // #54 dismiss previous android notification if no any Github notification is available (as it was read on another device) Utils.getNotificationManager(context).cancel(ANDROID_NOTIFICATION_ID); } }
From source file:com.compal.telephonytest.TelephonyTest.java
public void prepareSMS() { IntentFilter sendIntentFilter = new IntentFilter(SMS_SEND_ACTION); IntentFilter deliveryIntentFilter = new IntentFilter(SMS_DELIVERY_ACTION); IntentFilter dataSmsReceivedIntentFilter = new IntentFilter(DATA_SMS_RECEIVED_ACTION); mSendIntent = new Intent(SMS_SEND_ACTION); mDeliveryIntent = new Intent(SMS_DELIVERY_ACTION); dataSmsReceivedIntentFilter.addDataScheme("sms"); dataSmsReceivedIntentFilter.addDataAuthority("localhost", port.toString()); context.registerReceiver(SmsBroadcastReceiver, sendIntentFilter); context.registerReceiver(SmsBroadcastReceiver, deliveryIntentFilter); context.registerReceiver(SmsBroadcastReceiver, dataSmsReceivedIntentFilter); mText = mText + "_" + Long.toString(System.currentTimeMillis()); PendingIntent mSentIntent = PendingIntent.getBroadcast(getInstrumentation().getTargetContext(), 0, mSendIntent, PendingIntent.FLAG_ONE_SHOT); PendingIntent mDeliveredIntent = PendingIntent.getBroadcast(getInstrumentation().getTargetContext(), 0, mDeliveryIntent, PendingIntent.FLAG_ONE_SHOT); byte[] data = mText.getBytes(); mSmsManager.sendDataMessage(mPhoneNumber, null, port, data, mSentIntent, mDeliveredIntent); }
From source file:co.shunya.gita.player.MusicService.java
/** * Starts playing the next song. If manualUrl is null, the next song will be randomly selected * from our Media Retriever (that is, it will be a random song in the user's device). If * manualUrl is non-null, then it specifies the URL or path to the song that will be played * next.//from ww w . j a va 2s.com */ void playNextSong(Long id) { if (id == null || id < 0) { throw new IllegalArgumentException("id must be non nul +ve"); } setState(State.Stopped); relaxResources(false); // release everything except MediaPlayer try { // set the source of the media player to a manual URL or path Track playingItem = mRetriever.getItem(id); createMediaPlayerIfNeeded(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); if (playingItem == null) { Toast.makeText(this, "All Tracks of current category is been played", Toast.LENGTH_LONG).show(); processStopRequest(true); // stop everything! return; } // BusProvider.getInstance().post(playingItem); mCurrentID = id; mPlayer.setDataSource(playingItem.isDownloded() ? playingItem.getLocalUrl(this) : playingItem.getUrl()); mIsStreaming = playingItem.getUrl().startsWith("http:") || playingItem.getUrl().startsWith("https:"); mSongTitle = playingItem.getTitle(); setState(State.Preparing); updateUI(); setUpAsForeground(mSongTitle + " (loading)"); // Use the media button APIs (if available) to register ourselves for media button // events MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent); // Use the remote control APIs (if available) to set the playback state if (mRemoteControlClientCompat == null) { Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.setComponent(mMediaButtonReceiverComponent); mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent.getBroadcast( this /*context*/, 0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/)); RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat); } mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING); mRemoteControlClientCompat.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_STOP); // Update the remote controls mRemoteControlClientCompat.editMetadata(true) .putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, "Gita") .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, playingItem.getTitle()) .putBitmap(RemoteControlClientCompat.MetadataEditorCompat.METADATA_KEY_ARTWORK, mDummyAlbumArt) .apply(); // starts preparing the media player in the background. When it's done, it will call // our OnPreparedListener (that is, the onPrepared() method on this class, since we set // the listener to 'this'). // // Until the media player is prepared, we *cannot* call start() on it! mPlayer.prepareAsync(); // If we are streaming from the internet, we want to hold a Wifi lock, which prevents // the Wifi radio from going to sleep while the song is playing. If, on the other hand, // we are *not* streaming, we want to release the lock if we were holding it before. if (mIsStreaming) mWifiLock.acquire(); else if (mWifiLock.isHeld()) mWifiLock.release(); } catch (IOException ex) { Log.e("MusicService", "IOException playing next song: " + ex.getMessage()); ex.printStackTrace(); } }