理解PendingIntent以及在Notification中的使用

1.PendingIntent

PaddingIntent 待定的Intent
PaddingIntent所确定的跳转不会立即实现跳转,而是在满足一定条件后才会执行的跳转

2.获取PendingIntent的几个方法

2.1用于启动一个activity组件
public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags)
public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags, Bundle options)
2.2用于启动一个broadcast组件
public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)
2.3用于启动一个service组件
public static PendingIntent getService(Context context, int requestCode, Intent intent, int flags)
public static PendingIntent getForegroundService(Context context, int requestCode, Intent intent, int flags)

3.关于其中重要的四个参数

Context 
上下文;
requestCode
请求码,是对pendingIntent的描述,requestCode不同表示为不同的pendingIntent;
intent
一个intent对象
flags
FLAG_CANCEL_CURRENT:如果系统中存在一个相同的PendingIntent对象,那么就将现有的PendingIntent对象销毁,然后再重新生成一个PendingIntent对象;
FLAG_NO_CREATE:如果当前系统中不存在相同的PendingIntent对象,系统将不会创建该PendingIntent对象,而是直接返回null;
FLAG_ONE_SHOT:该PendingIntent只会作用一次,在该PendingIntent被触发后,PendingIntent将自动调用cancel()进行销毁;
FLAG_UPDATE_CURRENT:如果系统中有一个和你描述的PendingIntent对等的PendingIntent,那么系统将使用该PendingIntent对象,但是会使用新的Intent来更新之前的PendingIntent中的Intent对象数据;

4.PendingIntent在Android中的应用

4.1Notification中的使用

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void initNotification() {
    Intent intent=new Intent(this,MainActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this,11,intent,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification.Builder builder=new Notification.Builder(this);
    builder.setContentTitle("重大通知");
    builder.setContentText("这是什么重大通知");
    builder.setSmallIcon(R.mipmap.ic_launcher);
    builder.setContentIntent(pendingIntent);
    notificationManager.notify(notifyId,builder.build());
}
private void initView() {
    mTv= (TextView) findViewById(R.id.mTv);
    mTv.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onClick(View view) {

            initNotification();
        }
    });
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值