Android待确定意图PendingIntent的用法

5,406 阅读2分钟

PendingIntent是什么?

pendingIntent的字面意义:待确定的意图,等待的意图。pendingIntent是一种特殊的Intent,pendingIntent执行的操作实质上是参数传进来的Intent的操作,使用pendingIntent的目的在于它所包含的Intent的操作的执行是需要满足某些条件的。

Intent和PendingIntent的区别:

  1.  Intent是立刻执行的,而PendingIntent可以等到事件发生后触发,PendingIntent可以cancel。
  2. Intent在程序结束后即终止,而PendingIntent在程序结束后依然有效。
  3. PendingIntent自带Context,而Intent需要在某个Context内运行。
  4. Intent在原task中运行,PendingIntent在新的task中运行。

主要使用场景:

通知Notificatio的发送,短消息SmsManager的发送和警报器AlarmManager的执行等等。

要想得到一个PendindIntent对象,有以下四个静态方法:

PendingIntent.getActivity(Context, int, Intent, int) ,从系统取得一个用于启动一个Activity的PendingIntent对象

PendingIntent.getActivities(Context, int, Intent[], int)

PendingIntent.getBroadcast(Context, int, Intent, int),从系统取得一个用于向BroadcastReceiver的Intent广播的PendingIntent对象

PendingIntent.getService(Context, int, Intent, int),从系统取得一个用于启动一个Service的PendingIntent对象

示例一、Notification通知栏,使用PendingIntent.getActivity()

        //1.获取消息服务
        NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //2.实例化通知
        NotificationCompat.Builder nc = new NotificationCompat.Builder(this, "default");
        //通知默认的声音 震动 呼吸灯
        nc.setDefaults(NotificationCompat.DEFAULT_ALL);
        //通知标题
        nc.setContentTitle("标题");
        //通知内容
        nc.setContentText("内容");
        //设置通知的小图标
        nc.setSmallIcon(android.R.drawable.ic_popup_reminder);
        //设置通知的大图标
        nc.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        //设定通知显示的时间
        nc.setWhen(System.currentTimeMillis());
        //设置通知的优先级
        nc.setPriority(NotificationCompat.PRIORITY_MAX);
        //设置点击通知之后通知是否消失
        nc.setAutoCancel(true);
        //点击通知打开软件,使用PendingIntent.getActivity()
        Context application = getApplicationContext();
        Intent resultIntent = new Intent(application, MainActivity.class);
        resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(application, 0, resultIntent, 0);
        nc.setContentIntent(pendingIntent);
        //3.创建通知,得到build
        Notification notification = nc.build();
        //4.发送通知
        manager.notify(1, notification);

示例二、SmsManager发送短信,使用PendingIntent.getBroadcast()

SmsManager smsManage = SmsManager.getDefault();
Intent intent=new Intent("SEND_SMS_ACTION");
PendingIntent pendingIntent=PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
smsManage.sendTextMessage("13xxxxxxxxx", null, "这是一条短信", pendingIntent, null);

示例三、执行某个服务,使用PendingIntent.getService()

Intent intent = new Intent(context, taskService.class);
PendingIntent pi = PendingIntent.getService(context, 0, intent, 0);
/*重复闹钟*/
AlarmManager alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000, pi);