、私は最終的に、通知のアクションがクリックされたときに、任意の方法を実行するためにかなり簡単でクリーンな方法を見つけました。私のソリューションでは、通知を作成する1つのクラス(NotificationUtilsと呼ぶ)があり、通知のアクションがクリックされたときに実行されるIntentService静的内部クラスも含まれています。
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であなたの行動を実装し、<application>
タグ内にマニフェストにNotificationActionServiceを追加します:
<service android:name=".NotificationUtils$NotificationActionService" />
ここでのAndroidManifest.xmlに必要な変更に続いて、私のNotificationUtilsクラスは、あります要約:
- 通知を作成するクラスを作成します。
- このクラスの中で、IntentServiceの内部クラス(が静的であるか、または暗黙のエラー!)を追加して、クリックされたアクションに基づいてメソッドを実行できます。
- マニフェストでIntentServiceクラスを宣言します。
私は、通知バーに通知を通知して表示する通知マネージャーしか手に入れませんでした。通知をクリックすると、アクティビティが開きます。この動作を変更するには、アクティビティを開く代わりにメソッドを呼び出したり実行したりしていました。私はArfinのソリューションで作業しようとしています。私はこれをどうやって起こさせるのか分かりません。私は "DummyActivity"を作成しました。彼のソリューションの2番目の部分が "DummyActivity"になっているかどうかはわかりません。私はちょうど混乱しています。私は物事がスムーズに合うときが好きです。 – AnDev
yea AnDevあなたのダミーアクティビティが開始されたら、それらからブロードキャストを送信して終了します。親クラスでブロードキャストメッセージを受け取ります。すでに説明したように、そこから任意のメソッドを呼び出すことができます。放送を送信して終了することを除いて、ダミーアクティビティの中でさらに何もする必要はありません。 –