在Android中,PendingIntent是一种封装了意图(Intent)的对象,可以在稍后的时间执行。它常用于通知、闹钟和任务等场景。以下是创建PendingIntent的几种方法:
// 创建一个打开Activity的PendingIntent
Intent intent = new Intent(context, TargetActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 创建一个打开Activity并设置FLAG_UPDATE_CURRENT标志的PendingIntent
Intent intent = new Intent(context, TargetActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 创建一个打开Activity并设置FLAG_UPDATE_CURRENT标志的PendingIntent
Intent intent = new Intent(context, TargetActivity.class);
intent.putExtra("key", "value");
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 创建一个在指定时间后执行的PendingIntent
long triggerTime = System.currentTimeMillis() + 10000; // 10秒后触发
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, new Intent(context, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
// 创建一个打开Activity并设置FLAG_UPDATE_CURRENT标志的PendingIntent
Intent intent = new Intent(context, TargetActivity.class);
intent.putExtra("key", "value");
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 创建一个发送广播的PendingIntent
Intent broadcastIntent = new Intent("com.example.ACTION_BROADCAST");
broadcastIntent.putExtra("key", "value");
PendingIntent pendingBroadcast = PendingIntent.getBroadcast(context, requestCode, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
请注意,不同方法创建的PendingIntent具有不同的功能和用途。在使用PendingIntent时,请根据需要选择合适的方法。