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执行后的操作。PendingIntent常和alermanger 和notificationmanager一起使用。
Intent一般是用作Activity、Service、BroadcastReceiver之间传递数据;而Pendingintent一般用在 Notification上,可以理解为延迟执行的intent,PendingIntent是对Intent一个包装。
PendingIntent pIntent = PendingIntent.getActivity(this, 0, new Intent(this, NotifyActivity.class), 0);
详见代码:
private void showNotify(){
PendingIntent pIntent = PendingIntent.getActivity(this, 0, new Intent(this, NotifyActivity.class), 0); // pendingIntent
Notification notify = new Notification();
notify.icon = R.drawable.ic_launcher;
notify.tickerText = "您有一条新消息";
notify.defaults = Notification.DEFAULT_SOUND;
notify.when = System.currentTimeMillis();
notify.vibrate = new long[]{0, 50, 100, 150};
notify.contentIntent = pIntent;
notify.setLatestEventInfo(this, "通知", "http://blog.csdn.net/sunboy_2050", pIntent); // context, title, msg, pendingIntent
NotificationManager manager = (NotificationManager)getSystemService(this.NOTIFICATION_SERVICE);
manager.notify(0, notify);
}
通知结果:
GSM网络中android发送短信示例
private void showNotify222(){
String phone = "13212341234";
String msg = "http://blog.csdn.net/sunboy_2050";
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.homer.pendingintent.pendingbroadcast"), 0); // pendingIntent
SmsManager manager = SmsManager.getDefault();
if(msg.length() > 70) { // split msg length
List<String> msgList = manager.divideMessage(msg);
for (String msg2 : msgList) {
manager.sendTextMessage(phone, null, msg2, pIntent, null); // destinationAddress, scAddress, text, sentIntent, deliveryIntent
}
} else {
manager.sendTextMessage(phone, null, msg, pIntent, null);
}
}
AndroidManifest.xml 中 Application 节点内注册广播:
<receiver android:name=".PendingReceiver">
<intent-filter>
<action android:name="com.homer.pendingintent.pendingbroadcast" />
</intent-filter>
</receiver>
PendingReceiver 类 主要处理PendingIntent广播的事情,即发送短信成功后的提醒,实现如下:
public class PendingReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("com.homer.pendingintent.pendingbroadcast")) {
Toast.makeText(context, "Test PendingIntent Success", Toast.LENGTH_LONG).show();
}
}
}
AndroidManifest.xml 根节点下,添加短信发送权限:
<uses-permission android:name="android.permission.SEND_SMS" />
运行结果: