下面列出了怎么用android.app.PendingIntent的API类实例代码及写法,或者点击链接到github查看源代码。
public static Notification createSimpleNotification(
Context context, String title, String text, PendingIntent intent) {
return new Notification.Builder(
context, context.getString(R.string.notification_channel_id))
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.linphone_logo)
.setAutoCancel(true)
.setContentIntent(intent)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setCategory(Notification.CATEGORY_MESSAGE)
.setVisibility(Notification.VISIBILITY_PRIVATE)
.setPriority(Notification.PRIORITY_HIGH)
.setWhen(System.currentTimeMillis())
.setShowWhen(true)
.setColorized(true)
.setColor(context.getColor(R.color.notification_led_color))
.build();
}
private void listing11_24(Context context, NotificationCompat.Builder builder) {
Uri emailUri = Uri.parse("[email protected]");
// Listing 11-24: Adding a Notification action
Intent deleteAction = new Intent(context, DeleteBroadcastReceiver.class);
deleteAction.setData(emailUri);
PendingIntent deleteIntent = PendingIntent.getBroadcast(context, 0,
deleteAction, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(
new NotificationCompat.Action.Builder(
R.drawable.delete,
context.getString(R.string.delete_action),
deleteIntent).build());
}
private void actionInstallPackageQ(Uri uri) throws IOException {
PackageInstaller pi = getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
PackageInstaller.SessionParams.MODE_FULL_INSTALL);
int sessionId = pi.createSession(params);
// Show the progress dialog first
pi.registerSessionCallback(new InstallationProgressListener(this, pi, sessionId));
PackageInstaller.Session session = pi.openSession(sessionId);
doInstallPackageQ(uri, session, () -> {
// We have finished piping the streams, show the progress as 10%
session.setStagingProgress(0.1f);
// Commit the session
Intent intent = new Intent(this, DummyActivity.class);
intent.setAction(PACKAGEINSTALLER_CALLBACK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
session.commit(pendingIntent.getIntentSender());
});
}
@Test
public void testSerialize() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("Hello World!")
.setContentText("Hello World!")
.setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
.build();
String json = Json2Notification.from(context).with(notification).serialize();
System.out.println(json);
assertThat(json).isNotNull();
}
/**
* Returns the PendingIntent for completing |action| on the notification identified by the data
* in the other parameters.
*
* All parameters set here should also be set in
* {@link NotificationJobService#getJobExtrasFromIntent(Intent)}.
*
* @param context An appropriate context for the intent class and broadcast.
* @param action The action this pending intent will represent.
* @param notificationId The id of the notification.
* @param origin The origin to whom the notification belongs.
* @param profileId Id of the profile to which the notification belongs.
* @param incognito Whether the profile was in incognito mode.
* @param tag The tag of the notification. May be NULL.
* @param webApkPackage The package of the WebAPK associated with the notification. Empty if
* the notification is not associated with a WebAPK.
* @param actionIndex The zero-based index of the action button, or -1 if not applicable.
*/
private PendingIntent makePendingIntent(Context context, String action, String notificationId,
String origin, String profileId, boolean incognito, @Nullable String tag,
String webApkPackage, int actionIndex) {
Uri intentData = makeIntentData(notificationId, origin, actionIndex);
Intent intent = new Intent(action, intentData);
intent.setClass(context, NotificationService.Receiver.class);
intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_ID, notificationId);
intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_ORIGIN, origin);
intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_ID, profileId);
intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_INCOGNITO, incognito);
intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_TAG, tag);
intent.putExtra(
NotificationConstants.EXTRA_NOTIFICATION_INFO_WEBAPK_PACKAGE, webApkPackage);
intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_ACTION_INDEX, actionIndex);
return PendingIntent.getBroadcast(
context, PENDING_INTENT_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private static Object readObj(String type, Parcel in) {
switch (getBaseType(type)) {
case FORMAT_SLICE:
return Slice.CREATOR.createFromParcel(in);
case FORMAT_TEXT:
return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
case FORMAT_IMAGE:
return Icon.CREATOR.createFromParcel(in);
case FORMAT_ACTION:
return new Pair<>(
PendingIntent.CREATOR.createFromParcel(in),
Slice.CREATOR.createFromParcel(in));
case FORMAT_INT:
return in.readInt();
case FORMAT_TIMESTAMP:
return in.readLong();
case FORMAT_REMOTE_INPUT:
return RemoteInput.CREATOR.createFromParcel(in);
case FORMAT_BUNDLE:
return Bundle.CREATOR.createFromParcel(in);
}
throw new RuntimeException("Unsupported type " + type);
}
public PendingIntent getMarkAsReadIntent(Context context, int notificationId) {
long[] threadArray = new long[threads.size()];
int index = 0;
for (long thread : threads) {
Log.i(TAG, "Added thread: " + thread);
threadArray[index++] = thread;
}
Intent intent = new Intent(MarkReadReceiver.CLEAR_ACTION);
intent.setClass(context, MarkReadReceiver.class);
intent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
intent.putExtra(MarkReadReceiver.THREAD_IDS_EXTRA, threadArray);
intent.putExtra(MarkReadReceiver.NOTIFICATION_ID_EXTRA, notificationId);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.remote_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Controller.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
text, contentIntent);
// Send the notification.
// We use a string id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.remote_service_started, notification);
}
private void addPendingIntents(RemoteViews rv, boolean isPlaying, MediaInfo info) {
Intent playbackIntent = new Intent(ACTION_TOGGLE_PLAYBACK);
playbackIntent.setPackage(getPackageName());
PendingIntent playbackPendingIntent = PendingIntent
.getBroadcast(this, 0, playbackIntent, 0);
Intent stopIntent = new Intent(ACTION_STOP);
stopIntent.setPackage(getPackageName());
PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0);
rv.setOnClickPendingIntent(R.id.playPauseView, playbackPendingIntent);
rv.setOnClickPendingIntent(R.id.removeView, stopPendingIntent);
if (isPlaying) {
if (info.getStreamType() == MediaInfo.STREAM_TYPE_LIVE) {
rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_stop_sm_dark);
} else {
rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_pause_sm_dark);
}
} else {
rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_play_sm_dark);
}
}
private void sendNotification(String body, String title) {
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification.Builder notificationBuilder = (Notification.Builder) new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
private static void showMentionMoreNotification(final Context context,
final int count) {
if (AppContext.DEBUG) {
Log.d(NotificationReceiver.TAG,
"showMentionMoreNotification count=" + count);
}
final String title = "饭否消息";
final String message = "收到" + count + "条提到你的消息";
final Intent intent = new Intent(context, HomePage.class);
intent.setAction("DUMY_ACTION " + System.currentTimeMillis());
intent.putExtra(Constants.EXTRA_PAGE, 1);
final PendingIntent contentIntent = PendingIntent.getActivity(context,
0, intent, 0);
NotificationReceiver.showNotification(
NotificationReceiver.NOTIFICATION_ID_MENTION, context,
contentIntent, title, message, R.drawable.ic_notify_mention);
}
public static CustomTabsIntent.Builder getCustomTabIntent(@NonNull Context context,
@NonNull Story story,
@Nullable CustomTabsSession session) {
Intent upvoteStory = new Intent(context, UpvoteStoryService.class);
upvoteStory.setAction(UpvoteStoryService.ACTION_UPVOTE);
upvoteStory.putExtra(UpvoteStoryService.EXTRA_STORY_ID, story.id);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, upvoteStory, 0);
return new CustomTabsIntent.Builder(session)
.setToolbarColor(ContextCompat.getColor(context, R.color.designer_news))
.setActionButton(ImageUtils.vectorToBitmap(context,
R.drawable.ic_upvote_filled_24dp_white),
context.getString(R.string.upvote_story),
pendingIntent,
false)
.setShowTitle(true)
.enableUrlBarHiding()
.addDefaultShareMenuItem();
}
private void listing15_8() {
if (
ActivityCompat
.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PERMISSION_GRANTED ||
ActivityCompat
.checkSelfPermission(this, ACCESS_COARSE_LOCATION) == PERMISSION_GRANTED) {
// Listing 15-8: Requesting location updates using a Pending Intent
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
LocationRequest request = new LocationRequest()
.setInterval(60000 * 10) // Update every 10 minutes.
.setPriority(LocationRequest.PRIORITY_NO_POWER);
final int locationUpdateRC = 0;
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
Intent intent = new Intent(this, MyLocationUpdateReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, locationUpdateRC, intent, flags);
fusedLocationClient.requestLocationUpdates(request, pendingIntent);
}
}
private static void disableMotionTrackingDueToErrors(Context context) {
final long requested = getInternalPrefsLong(REQUESTED);
final long received = getInternalPrefsLong(RECEIVED);
Home.toaststaticnext("DISABLED MOTION TRACKING DUE TO FAILURES! See Error Log!");
final String msg = "Had to disable motion tracking feature as it did not seem to be working and may be incompatible with your phone. Please report this to the developers using the send logs feature: " + requested + " vs " + received + " " + JoH.getDeviceDetails();
UserError.Log.wtf(TAG, msg);
UserError.Log.ueh(TAG, msg);
Pref.setBoolean("motion_tracking_enabled", false);
evaluateRequestReceivedCounters(true, context); // mark for disable
setInternalPrefsLong(REQUESTED, 0);
setInternalPrefsLong(RECEIVED, 0);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent intent = new Intent(xdrip.getAppContext(), ErrorsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(xdrip.getAppContext(), 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
builder.setContentText("Shut down motion detection! See Error Logs - Please report to developer" + JoH.dateTimeText(JoH.tsl()));
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Problem with motion detection!");
NotificationManagerCompat.from(context).notify(VEHICLE_NOTIFICATION_ERROR_ID, builder.build());
}
private static Notification buildAlertGroupSummaryNotification(Context context,
Location location,
Alert alert,
int notificationId) {
return new NotificationCompat.Builder(context, GeometricWeather.NOTIFICATION_CHANNEL_ID_ALERT)
.setSmallIcon(R.drawable.ic_alert)
.setContentTitle(alert.getDescription())
.setGroup(NOTIFICATION_GROUP_KEY)
.setColor(
ContextCompat.getColor(
context,
TimeManager.getInstance(context).isDayTime()
? R.color.lightPrimary_5
: R.color.darkPrimary_5
)
).setGroupSummary(true)
.setOnlyAlertOnce(true)
.setContentIntent(
PendingIntent.getActivity(
context,
notificationId,
IntentHelper.buildMainActivityShowAlertsIntent(location),
PendingIntent.FLAG_UPDATE_CURRENT
)
).build();
}
public void setNextAlarm(Context context) {
AlarmManager aManager = (AlarmManager) context
.getSystemService(Service.ALARM_SERVICE);
Calendar tcalendar = Calendar.getInstance();
tcalendar.setTimeInMillis(System.currentTimeMillis());
tcalendar.add(Calendar.DAY_OF_YEAR, +1);
tcalendar.set(Calendar.HOUR_OF_DAY, 0);
tcalendar.set(Calendar.MINUTE, 19);
tcalendar.set(Calendar.SECOND, 19);
Intent intent = new Intent(context, LessonsWidgetProvider_4_1.class);
intent.setAction("zq.whu.zhangshangwuda.ui.lessons.widget_4_1.today");
PendingIntent work = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
aManager.cancel(work);
aManager.set(AlarmManager.RTC, tcalendar.getTimeInMillis(), work);
Log.v("zq.whu.zhangshangwuda.ui.lessons.widget_4_1", "设置定时更新成功");
}
public void sendBasicNotification(String notif) {
NotificationManager nm = (NotificationManager) StaticData.globalContext.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.alert_dark_frame;
CharSequence contentTitle = "TinyGSN notification";
CharSequence tickerText = notif;
long when = System.currentTimeMillis();
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(StaticData.globalContext)
.setSmallIcon(icon)
.setContentTitle(contentTitle)
.setContentText(tickerText);
Intent notificationIntent = new Intent(StaticData.globalContext, ActivityViewData.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(StaticData.globalContext);
stackBuilder.addParentStack(ActivityViewData.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent contentIntent = PendingIntent.getActivity(StaticData.globalContext, 0,
notificationIntent, 0);
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
nm.notify(notify_id++, mBuilder.build());
}
private void Notify() {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
final PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) Calendar.getInstance().getTimeInMillis(), intent, 0);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(channel_Id + " channel");
for (int i = (messages.size() > 5 ? messages.size() - 5 : 0); i < messages.size(); i++) {
DeveloperMessage message = messages.get(i);
String line = message.getName() + ":\t" + message.getText();
inboxStyle.addLine(line);
}
int count = messages.size();
String summary = count + (count > 1 ? " new messages" : " new message");
inboxStyle.setSummaryText(summary);
//Todo: change the small icon with an xml icon
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel_Id)
.setSmallIcon(R.mipmap.ic_launcher) //Todo: change the small icon with an xml icon
.setStyle(inboxStyle)
.setContentIntent(pendingIntent)
.setContentTitle(channel_Id + " channel")
.setContentText(summary);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
android.app.NotificationChannel notificationChannel = new android.app.NotificationChannel(channel_Id, "Maker Toolbox", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(id, builder.build());
}
/**
* When scanning with PendingIntent on Android Oreo or newer, the app may get killed
* by the system. To stop scanning, the same {@link PendingIntent} must be used that was
* used to start scanning. Comparing intents is done using {@link Intent#filterEquals(Intent)}.
*
* @return The PendingIntent that is to be used to stop scanning. It is equal to one used to
* start scanning if the callbackIntent is equal to one used to start scanning.
*/
@NonNull
private PendingIntent createStoppingPendingIntent(@NonNull final Context context,
@NonNull final PendingIntent callbackIntent) {
// The PendingIntent ID is derived from the user's callbackIntent.
final int id = callbackIntent.hashCode();
// Since Android 8 it has to be an explicit intent
final Intent intent = new Intent(context, PendingIntentReceiver.class);
intent.setAction(PendingIntentReceiver.ACTION);
return PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private void enableTagWriteMode() {
IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter[] mWriteTagFilters = new IntentFilter[]{intentFilter};
PendingIntent nfcPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
nfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, mWriteTagFilters, null);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
//启动首页
Intent intent = new Intent();
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addCategory("com.android.framework.MAINPAGE");
PendingIntent restartIntent = PendingIntent.getActivity(getInstance(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//退出程序
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);
ActivityManager.getInstance().finishAllActivityWithoutClose();
}
private void initializeServiceIntent() {
if (serviceIntent == null) {
synchronized (this) {
if (serviceIntent == null) {
serviceIntent = PendingIntent.getService(this, Constants.MISSED_READING_SERVICE_ID, new Intent(this, this.getClass()), 0);
}
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
Intent displayIntent = new Intent(context, MyDisplayActivity.class);
String text = intent.getStringExtra(CONTENT_KEY);
Notification notification = new Notification.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(text)
.extend(new Notification.WearableExtender()
.setDisplayIntent(PendingIntent.getActivity(context, 0, displayIntent,
PendingIntent.FLAG_UPDATE_CURRENT)))
.build();
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);
Toast.makeText(context, context.getString(R.string.notification_posted), Toast.LENGTH_SHORT).show();
}
@Override
public void onReceive(Context context, Intent intent) {
Boolean enabled = PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean("notification-enabled", false);
Log.d(TAG, "Alarm received; enabled=" + enabled.toString());
if (enabled) {
//Locale locale = Locale.getDefault();
//Calendar.getInstance().getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, locale)
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.glyphicons_152_check_white)
.setContentTitle(context.getString(R.string.reminder_title))
.setAutoCancel(true)
.setContentText(context.getString(R.string.reminder_text));
Intent resultIntent = new Intent(context, Tickmate.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());
}
}
private void schedulePingAlarm() {
Intent intentAlarm = new Intent();
intentAlarm.setAction(ACTION_PING_ALARM);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, HEARTBEAT_ALARM, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + pingInterval, pendingIntent);
} else {
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + pingInterval, pendingIntent);
}
}
/**
* Cancel registered notification
* @param requestCode Pending intent request code you want to cancel
*/
public static void cancel(int requestCode) {
Context context = getContext();
// get pending intent
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, NotificationReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// cancel it
alarmManager.cancel(sender);
}
private void deleteTimer() {
cancelCountdownNotification();
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(Constants.ACTION_SHOW_ALARM, null, this,
TimerNotificationService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarm.cancel(pendingIntent);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Timer deleted.");
}
}
private void registerAlarmManager( long duration ) {
AlarmManager alarmManager = (AlarmManager) getSystemService( Context.ALARM_SERVICE );
Intent intent = new Intent( ACTION_SHOW_ALARM, null, this, TimerService.class );
PendingIntent pendingIntent = PendingIntent.getService( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT );
long time = System.currentTimeMillis() + duration;
alarmManager.setExact( AlarmManager.RTC_WAKEUP, time, pendingIntent );
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
static void sendChooserIntent(boolean saveLastUsed, Activity activity,
Intent sharingIntent,
@Nullable TargetChosenCallback callback) {
synchronized (LOCK) {
if (sTargetChosenReceiveAction == null) {
sTargetChosenReceiveAction = activity.getPackageName() + "/"
+ TargetChosenReceiver.class.getName() + "_ACTION";
}
Context context = activity.getApplicationContext();
if (sLastRegisteredReceiver != null) {
context.unregisterReceiver(sLastRegisteredReceiver);
// Must cancel the callback (to satisfy guarantee that exactly one method of
// TargetChosenCallback is called).
// TODO(mgiuca): This should be called immediately upon cancelling the chooser,
// not just when the next share takes place (https://crbug.com/636274).
sLastRegisteredReceiver.cancel();
}
sLastRegisteredReceiver = new TargetChosenReceiver(saveLastUsed, callback);
context.registerReceiver(
sLastRegisteredReceiver, new IntentFilter(sTargetChosenReceiveAction));
}
Intent intent = new Intent(sTargetChosenReceiveAction);
intent.setPackage(activity.getPackageName());
intent.putExtra(EXTRA_RECEIVER_TOKEN, sLastRegisteredReceiver.hashCode());
final PendingIntent pendingIntent = PendingIntent.getBroadcast(activity, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
Intent chooserIntent = Intent.createChooser(sharingIntent,
activity.getString(R.string.share_link_chooser_title),
pendingIntent.getIntentSender());
if (sFakeIntentReceiverForTesting != null) {
sFakeIntentReceiverForTesting.setIntentToSendBack(intent);
}
fireIntent(activity, chooserIntent);
}
private void scheduleRecommendationUpdate(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent recommendationIntent = new Intent(context, RecommendationsService.class);
PendingIntent alarmIntent = PendingIntent.getService(context, 0, recommendationIntent, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
INITIAL_DELAY,
AlarmManager.INTERVAL_HALF_HOUR,
alarmIntent);
}