下面列出了android.app.PendingIntent#getBroadcast ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Uses {@link AlarmManager} to schedule an intent that will cause scheduled tasks to be executed.
* Replaces any existing scheduled-task intent, so the provided execute time should be for the
* next/earliest scheduled task.
*/
static void issueScheduledTaskIntent(Context context, long executeMs) {
Intent intent = createScheduledTaskintent(context);
// Create a pending intent that will cause the AlarmManager to fire the above intent.
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Schedule the pending intent after the appropriate delay.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
try {
alarmManager.set(AlarmManager.RTC, executeMs, pendingIntent);
} catch (SecurityException exception) {
logger.warning("Unable to schedule task: %s", exception);
}
}
@Singleton @Provides RootInstallationRetryHandler provideRootInstallationRetryHandler(
InstallManager installManager) {
Intent retryActionIntent = new Intent(application, RootInstallNotificationEventReceiver.class);
retryActionIntent.setAction(RootInstallNotificationEventReceiver.ROOT_INSTALL_RETRY_ACTION);
PendingIntent retryPendingIntent = PendingIntent.getBroadcast(application, 2, retryActionIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action action =
new NotificationCompat.Action(R.drawable.ic_refresh_action_black,
application.getString(R.string.generalscreen_short_root_install_timeout_error_action),
retryPendingIntent);
PendingIntent deleteAction = PendingIntent.getBroadcast(application, 3,
retryActionIntent.setAction(
RootInstallNotificationEventReceiver.ROOT_INSTALL_DISMISS_ACTION),
PendingIntent.FLAG_UPDATE_CURRENT);
int notificationId = 230498;
return new RootInstallationRetryHandler(notificationId,
application.getSystemNotificationShower(), installManager, PublishRelay.create(), 0,
application, new RootInstallErrorNotificationFactory(notificationId,
BitmapFactory.decodeResource(application.getResources(), R.mipmap.ic_launcher), action,
deleteAction));
}
/**
* Returns the PendingIntent for completing |action| on the notification identified by the data
* in the other parameters.
*
* @param action The action this pending intent will represent.
* @paramn 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(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(mAppContext, 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(mAppContext, PENDING_INTENT_REQUEST_CODE, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
public static void setDailyAlarm(Context context) {
Intent notifyIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, 0, notifyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
// TODO(smcgruer): Allow user to configure the time.
final Calendar cal = Calendar.getInstance();
if (cal.get(Calendar.HOUR_OF_DAY) >= 20)
cal.add(Calendar.DATE, 1);
cal.set(Calendar.HOUR_OF_DAY, 20);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
private static boolean parseTaskAndReturnIfNeedExecuteImmediately(Context context, String task, String taskTrigger) {
String[] splitTask = task.split(" ");
int splitTaskLength = splitTask.length;
for (int i = 0; i < splitTaskLength; i++) {
switch (splitTask[i]) {
case "-d":
if (splitTaskLength >= i + 1) {
long delayAtSeconds = Long.parseLong(splitTask[i + 1]);
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, TasksNeedExecuteReceiver.class)
.putExtra("id", -6)
.putExtra("task", task.replace(" -d " + splitTask[i + 1], ""))
.putExtra("repeat", "-1")
.putExtra("hour", -1)
.putExtra("minute", -1);
int requestCode = (task + new Date().toString()).hashCode();
PendingIntent pendingIntent =
PendingIntent.getBroadcast(
context,
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
createDelayTasks(alarmMgr, delayAtSeconds, pendingIntent);
if (taskTrigger != null) {//定时或无撤回判断能力或目前不计划实现撤销的任务直接null
AppPreferences appPreferences = new AppPreferences(context);
appPreferences.put(taskTrigger, appPreferences.getString(taskTrigger, "") + requestCode + ",");
}
return false;
}
break;
default:
break;
}
}
return true;
}
public void setAlarm(Context context, Alarm alarm)
{
disableAllAlarms(context);
if (alarm==null || alarm.nextNotificationTime==null) return;
Bundle bundle = new Bundle();
bundle.putString("ALARM_GUID", alarm.guid );
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtras(bundle);
this.pi = PendingIntent.getBroadcast(context, 0, intent, 0);
this.am.set(AlarmManager.RTC_WAKEUP, alarm.nextNotificationTime.getTime(), this.pi);
}
private static void disableBackup() {
AlarmManager am = (AlarmManager) GlobalApplication.getAppContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent("NARRATE_BACKUP");
intent.setClass(GlobalApplication.getAppContext(), AlarmReceiver.class);
PendingIntent reminderNotificationIntent = PendingIntent.getBroadcast(GlobalApplication.getAppContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(reminderNotificationIntent);
}
/**
* Creates PendingIntent to notify the widget of a button click.
*
* @param context
* @param accId
* @return
*/
private static PendingIntent getLaunchPendingIntent(Context context, long accId, boolean activate ) {
Intent launchIntent = new Intent(SipManager.INTENT_SIP_ACCOUNT_ACTIVATE);
launchIntent.putExtra(SipProfile.FIELD_ID, accId);
launchIntent.putExtra(SipProfile.FIELD_ACTIVE, activate);
Log.d(THIS_FILE, "Create intent "+activate);
PendingIntent pi = PendingIntent.getBroadcast(context, (int)accId,
launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return pi;
}
@Override
public void onReceive(Context context, Intent intent) {
// only run if the app has run before and main has extracted asserts
String action = intent.getAction();
boolean run_boot = Tools.getBoolean("run_boot", false, context);
boolean rootAccess = Tools.rootAccess(context);
if (Intent.ACTION_BOOT_COMPLETED.equals(action) && rootAccess && run_boot) {
Log.d(TAG, " Started action " + action + " run_boot " + run_boot);
if (Tools.getBoolean("prop_run", false, context) && Tools.getBoolean("apply_props", false, context))
ContextCompat.startForegroundService(context, new Intent(context, PropsService.class));
ContextCompat.startForegroundService(context, new Intent(context, BootService.class));
if (Tools.getBoolean("apply_su", false, context) && Tools.SuVersionBool(Tools.SuVersion(context))) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent serviceIntent = new Intent("com.bhb27.isu.services.SuServiceReceiver.RUN");
serviceIntent.putExtra("RUN", 100);
serviceIntent.setClass(context, SuServiceReceiver.class);
serviceIntent.setAction("RUN");
PendingIntent pi = PendingIntent.getBroadcast(context, 100, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + Integer.valueOf(Tools.readString("apply_su_delay", "0", context)), pi);
}
} else Log.d(TAG, "Not Started action " + action + " rootAccess " + rootAccess + " run_boot " + run_boot);
}
public static void stopReplyCheckerService(Context context){
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent senderstop = PendingIntent.getBroadcast(context,
REPLY_CHECKER_INTENT_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManagerstop = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManagerstop.cancel(senderstop);
}
/**
* Set up main alarm
*/
private void setAlarm(Person person) {
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra(Constants.NAME, person.getName());
intent.putExtra(Constants.WHEN, context.getString(R.string.today));
intent.putExtra(Constants.TIME_STAMP, person.getTimeStamp());
long triggerAtMillis = setupCalendarYear(person, 0);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(),
(int) person.getTimeStamp(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
setAlarmDependingOnApi(alarmManager, triggerAtMillis, pendingIntent);
}
protected void startAlarmTimer(long nextTime) {
Log.i(LOG_TAG, "startAlarmTimer ELAPSED_REALTIME_WAKEUP! nextTime=" + nextTime);
Intent intent = new Intent();
intent.setAction(this.getPackageName() + ACTION_KEEP_LIVE);
this.mCheckSender = PendingIntent.getBroadcast(this, 100, intent, 0);
try {
if (am != null && mCheckSender != null) {
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + nextTime, mCheckSender);
}
} catch (Exception e) {
Log.e(LOG_TAG, "startAlarmTimer fail", e);
}
}
private PendingIntent intentFor(String intentType, String id, String destination, String content, int partIndex, int totalParts) {
Intent intent = new Intent(intentType);
intent.putExtra("id", id);
intent.putExtra("destination", destination);
intent.putExtra("content", content);
intent.putExtra("partIndex", partIndex);
intent.putExtra("totalParts", totalParts);
// Use a random number for the PendingIntent's requestCode - we
// will never want to cancel these intents, and we do not want
// collisions. There is a small chance of collisions if two
// SMS are in-flight at the same time and are given the same id.
return PendingIntent.getBroadcast(parent, UNUSED_REQUEST_CODE, intent, PendingIntent.FLAG_ONE_SHOT);
}
/**
* 启动心跳监控
*
* @param period
*/
public static void startHeart(Context context) {
getAlarmManager(context);
// 操作:发送一个广播,广播接收后Toast提示定时操作完成
if (sender == null) {
Intent intent = new Intent();
intent.setAction(AlarmReceiver.ACTION);
sender = PendingIntent.getBroadcast(context, 0, intent, 0);
}
// 开始时间
long firstime = SystemClock.elapsedRealtime() + 10 * 1000L;
Log.i(NettyAlarmManager.class.getName(), "startHeart");
// 一个周期,不停的发送广播
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, PERIOD, sender);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int appWidgetId : appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_more_3x3);
setWidgetTheme(context, remoteViews);
preLoadWeather(context, remoteViews);
Intent intentRefreshService = new Intent(context, MoreWidgetProvider.class);
intentRefreshService.setAction(Constants.ACTION_FORCED_APPWIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intentRefreshService, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_button_refresh, pendingIntent);
Intent intentStartActivity = new Intent(context, MainActivity.class);
PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 0,
intentStartActivity, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_root, pendingIntent2);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
context.startService(new Intent(context, MoreWidgetService.class));
}
public static PendingIntent createDeleteIntent(Context context, int requestCode, @Nullable Chat chat) {
return PendingIntent.getBroadcast(context, requestCode, FFMBroadcastReceiver.deleteIntent(chat), PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public void onCreate() {
context = getApplicationContext();
pendingJobs = new ArrayList<>();
SharedPreferences preferences = getSharedPreferences("appSettings",MODE_PRIVATE);
useFFMPEGmuxer = preferences.getBoolean("pref_muxer",true);
PRDownloader.initialize(context);
/** Create notification channel if not present */
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
CharSequence name = context.getString(R.string.channel_name);
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel("channel_01", name, importance);
notificationChannel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"Download",importance);
notificationManager.createNotificationChannel(channel);
}
/** Setting Power Manager and Wakelock */
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "app:Wakelock");
wakeLock.acquire();
Intent notificationIntent = new Intent(context, DownloadActivity.class);
contentIntent = PendingIntent.getActivity(context,
0, notificationIntent, 0);
Intent newintent = new Intent(context, SongBroadCast.class);
newintent.setAction("com.kpstv.youtube.STOP_SERVICE");
cancelIntent =
PendingIntent.getBroadcast(context, 5, newintent, 0);
setUpdateNotificationTask();
super.onCreate();
}
private static boolean isUpdateTimeAlarmOn(Context context) {
Intent intent = new Intent(UPDATE_WIDGET_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_NO_CREATE);
return pendingIntent != null;
}
void snoozeAlarm(AlarmModel alarm) {
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR_OF_DAY, alarm.getHour());
calendar.set(Calendar.MINUTE, alarm.getMinute());
calendar.set(Calendar.SECOND, alarm.getSecond());
calendar.set(Calendar.DAY_OF_MONTH, alarm.getDay());
calendar.set(Calendar.MONTH, alarm.getMonth() - 1);
calendar.set(Calendar.YEAR, alarm.getYear());
// set snooze interval
calendar.add(Calendar.MINUTE, alarm.getSnoozeInterval());
alarm.setSecond(calendar.get(Calendar.SECOND));
alarm.setMinute(calendar.get(Calendar.MINUTE));
alarm.setHour(calendar.get(Calendar.HOUR_OF_DAY));
alarm.setDay(calendar.get(Calendar.DAY_OF_MONTH));
alarm.setMonth(calendar.get(Calendar.MONTH) - 1);
alarm.setYear(calendar.get(Calendar.YEAR));
alarm.setAlarmId((int) System.currentTimeMillis());
getAlarmDB().update(alarm);
Log.e(TAG, "snooze data - " + alarm.toString());
int alarmId = alarm.getAlarmId();
Intent intent = new Intent(mContext, AlarmReceiver.class);
intent.putExtra("intentType", ADD_INTENT);
intent.putExtra("PendingId", alarm.getId());
PendingIntent alarmIntent = PendingIntent.getBroadcast(mContext, alarmId, intent, 0);
AlarmManager alarmManager = this.getAlarmManager();
String scheduleType = alarm.getScheduleType();
if (scheduleType.equals("once")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
} else if (scheduleType.equals("repeat")) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarm.getInterval() * 1000, alarmIntent);
} else {
Log.d(TAG, "Schedule type should either be once or repeat");
}
}
/**
* Create an PendingIntent to execute when the notification is explicitly dismissed by the user.
*
* @see android.app.Notification#setDeleteIntent(PendingIntent)
*
* @param entry
* @return PendingIntent
*/
public PendingIntent getDeleteIntent(NotificationEntry entry) {
Intent intent = new Intent(ACTION_CANCEL);
intent.putExtra(KEY_ENTRY_ID, entry.ID);
return PendingIntent.getBroadcast(mContext, genIdForPendingIntent(), intent, 0);
}