经过几次反复试验和错误,我终于找到了一种相当简单明了的方法来在单击通知的操作时运行任意方法。在我的解决方案中,有一个类(我将其称为 NotificationUtils)创建通知,还包含一个 IntentService 静态内部类,该类将在单击通知上的操作时运行。这是我的 NotificationUtils 类,然后是对 AndroidManifest.xml 的必要更改:
public class NotificationUtils {
public static final int NOTIFICATION_ID = 1;
public static final String ACTION_1 = "action_1";
public static void displayNotification(Context context) {
Intent action1Intent = new Intent(context, NotificationActionService.class)
.setAction(ACTION_1);
PendingIntent action1PendingIntent = PendingIntent.getService(context, 0,
action1Intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Sample Notification")
.setContentText("Notification text goes here")
.addAction(new NotificationCompat.Action(R.drawable.ic_launcher,
"Action 1", action1PendingIntent));
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
public static class NotificationActionService extends IntentService {
public NotificationActionService() {
super(NotificationActionService.class.getSimpleName());
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
DebugUtils.log("Received notification action: " + action);
if (ACTION_1.equals(action)) {
// TODO: handle action 1.
// If you want to cancel the notification: NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID);
}
}
}
现在只需在 onHandleIntent 中实现您的操作,并将 NotificationActionService 添加到<application>
标签内的清单中:
<service android:name=".NotificationUtils$NotificationActionService" />
概括:
- 创建一个将创建通知的类。
- 在该类中,添加一个 IntentService 内部类(确保它是静态的,否则您将收到一个神秘的错误!),它可以根据单击的操作运行任何方法。
- 在清单中声明 IntentService 类。