PendingIntent有哪些初始化方法,各自的场景是什么,又是怎么使用的?
时间: 2024-09-18 22:05:54 浏览: 40
PendingIntent是Android系统提供的一种延迟执行的操作请求,主要用于启动Activity、Service或BroadcastReceiver。它有几种常见的初始化方法:
1. **通过Intent.createChooser()**: 这种方法常用于设置系统的"选择应用"对话框,用户可以选择执行某个操作的应用。例如:
```java
Intent intent = new Intent(Intent.ACTION_SEND);
// 设置意图类型
intent.setType("text/plain");
List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0);
// 创建PendingIntent
PendingIntent pi = PendingIntent.getActivities(this, 0, intent, 0);
// 显示选择应用的对话框
startActivityForResult(chooseActivity(pi), REQUEST_CODE);
```
2. **通过Context.startActivity()**: 当你需要立即启动一个Activity,并希望在未来可以取消这个启动请求时,可以创建一个PendingIntent。例如:
```java
Intent launchIntent = new Intent(this, MyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launchIntent, 0);
// 启动Activity
startActivity(pendingIntent);
```
3. **通过getBroadcast()**: 用于注册BroadcastReceiver并获取PendingIntent,以便在将来发送广播时触发接收者。例如:
```java
IntentFilter filter = new IntentFilter();
BroadcastReceiver receiver = new MyReceiver();
pendingIntent = PendingIntent.getBroadcast(context, 0, filter, 0);
registerReceiver(receiver, pendingIntent);
```
阅读全文