PendingIntent

本文深入解析Android开发中Intent和PendingIntent的概念、功能和应用场景,包括它们如何用于快速启动活动、发送短信、设置闹钟以及在通知中实现跳转等功能。文章详细阐述了两者之间的关键区别,如Intent的即时执行与PendingIntent的延迟执行特性,以及如何在不同场景下灵活运用这两个组件,特别关注于它们与Notification、AlarmManager、SmsManager的交互方式。通过具体的代码示例,展示了如何在实际应用中创建、配置和使用PendingIntent,以实现高效、灵活的通知、短信发送和定时任务管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

intent英文意思是意图,pending表示即将发生或来临的事情。 
PendingIntent这个类用于处理即将发生的事情。比如通知的点击效果:在通知Notification中用于跳转页面,但不是马上跳转。 

Intent 是及时启动,intent 随所在的activity 消失而消失。 
PendingIntent 可以看作是对intent的包装,通常通过getActivity,getBroadcast ,getService来得到pendingintent的实例,当前activity并不能马上启动它所包含的intent,而是在外部执行 pendingintent时,调用intent的。正由于pendingintent中 保存有当前App的Context,使它赋予外部App一种能力,使得外部App可以如同当前App一样的执行pendingintent里的 Intent, 就算在执行时当前App已经不存在了,也能通过存在pendingintent里的Context照样执行Intent。另外还可以处理intent执行后的操作。常和alermanger 和notificationmanager一起使用。 
Intent一般是用作Activity、Sercvice、BroadcastReceiver之间传递数据,而Pendingintent,一般用在 Notification上,可以理解为延迟执行的intent
PendingIntent是对Intent一个包装。 

Java代码 
  1. private void showNotify(){   
  2.         Notification notice=new Notification();   
  3.         notice.icon=R.drawable.icon;   
  4.         notice.tickerText="您有一条新的信息";   
  5.         notice.defaults=Notification.DEFAULT_SOUND;
  6. Intent intent=new Intent(this,Activity2.class);   
  7. notice.setLatestEventInfo(this"通知""开会"
  8.             PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT));
  9. //显示通知的时候不会跳转,点击之后才跳转。 FLAG是取消当前已有的,重新创建个新的
  10.         NotificationManager manager=(NotificationManager)getSystemService(this.NOTIFICATION_SERVICE);   
  11.         manager.notify(0,notice);   
  12.     }  

对于Android的Intent相关内容,可能部分初级Android开发者不知道PendingIntent是干什么的? 对于Notification和SmsManager中的sendMessage以及AlarmManager中的set这些方法中均有PendingIntent,到底PendingIntent和Intent有哪些不同呢?

官方解释:An Intent is something that is used right now; a PendingIntent is something that may create an Intent in the future. You will use a PendingIntent with Notifications, AlarmManager, etc.


Intent是意图的意思,它是一个马上执行的东西,比如Activity跳转,执行

Intent intent = new Intent();

intent.setClass(Test1.this, Test2.class);

startActivity(intent);

那么Intent会马上从Test1跳转到Test2


PendingIntent中Pending意思为即将发生的,待定。也就是不确定什么时候会发生,可能是未来的某个时间发生,可以理解为一种延迟的Intent,但是它一般会由别的程序触发。比如短信发送时,本对象用于跟踪未来短信的接收情况,主要是短信回执报告和发送成功或失败,因为GSM通讯到RIL再到移动基站的过程很漫长,通过开一个Thread等待对于我们的应用是比较麻烦和耗资源,而Android的框架层的TelephonyManager底层远程服务会跟踪,最终通过PendingIntent来跟踪。

Intent intent = new Intent(this, Test2.class);

PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

PendingIntent可以封装Activity,BroadcastReceiver,Service,与Intent有区别的是PendingIntent可以脱离应用程序而存在


GSM网络中android发送短信示例

String msg ="你好,美女";

String number = "135****6784";

SmsManager sms = SmsManager.getDefault();


PendingIntent pi = PendingIntent.getBroadcast(SmsActivity.this,0,new Intent(...),0);

sms.sendTextMessage(number, null, msg, pi, null);

Toast.makeText(SmsActivity.this,"发送成功",Toast.LENGHT_LONG).show();


方法SmsManager.sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent):短信发送成功,进行通知

PendingIntent sentIntent:当短信发出时,成功的话sendIntent会把其内部的描述的intent广播出去,当然失败之后会产生错误代码,并通过 android.app.PendingIntent.OnFinished进行回调("Callback");

PendingIntent deliveryIntent:是当消息已经传递给收信人后所进行的Intent广播;

如果你的BroadcastReveiver注册接收相应的消息,你就会收到相应的Intent,这时候就可以根据Intent的Action,执行相应的动作,这就是上面说的in the future的含义;

public class SendSMSActivity extends AppCompatActivity {
    private EditText to;
    private EditText input;
    private Button send;

    private SendStatueReceiver receiver;
    private IntentFilter filter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_sms);

        to= (EditText) findViewById(R.id.et_to);
        input= (EditText) findViewById(R.id.et_input);
        send= (Button) findViewById(R.id.btn_send);

        //注册广播接收器
        filter=new IntentFilter();
        filter.addAction("SENT_SMS_ACTION");
        receiver=new SendStatueReceiver();
        registerReceiver(receiver,filter);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SmsManager manager=SmsManager.getDefault();
                Intent intent=new Intent("SENT_SMS_ACTION")
                PendingIntent pi=PendingIntent.getBroadcast(SendSMSActivity.this,0,intent,0);
                manager.sendTextMessage(to.getText().toString(),null,input.getText().toString(),
                        pi,null);
            }
        });
    }

    //广播接收器,用于监听短信的发送状态
    class SendStatueReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (getResultCode()==RESULT_OK){
                //短信发送成功
            }else{
                //短信发送失败
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}



还有一个问题就是怎么区分PendingIntent,主要取消的时候要用到,requestCode可以区分,但系统还是根据Intent的Action去区分的,如果Intent设置了Class,classData,取消的时候Intent一定要设置要相同的,不然取消不掉就可能出现取消后,Alarm还会响的问题,PendingIntent用的地方蛮多的,像 Notifications, AlarmManager等都会用到。。。

在Android中有以下flag:

FLAG_CANCEL_CURRENT:如果当前系统中已经存在一个相同的PendingIntent对象,那么就将先将已有的PendingIntent取消,然后重新生成一个PendingIntent对象。

FLAG_NO_CREATE:如果当前系统中不存在相同的PendingIntent对象,系统将不会创建该PendingIntent对象而是直接返回null。

FLAG_ONE_SHOT:该PendingIntent只作用一次,如果该PendingIntent对象已经触发过一次,那么下次再获取该PendingIntent并且再触发时,系统将会返回一个SendIntentException,在使用这个标志的时候一定要注意哦。

FLAG_UPDATE_CURRENT:如果系统中已存在该PendingIntent对象,那么系统将保留该PendingIntent对象,但是会使用新的Intent来更新之前PendingIntent中的Intent对象数据,例如更新Intent中的Extras。这个非常有用,例如之前提到的,我们需要在每次更新之后更新Intent中的Extras数据,达到在不同时机传递给MainActivity不同的参数,实现不同的效果。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值