在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時,請根據需要選擇合適的方法。