LoginSignup
6
11

More than 5 years have passed since last update.

【Android】通知(Notification)に「ボタン」を表示する

Last updated at Posted at 2017-11-12

通知(Notification)からショートカット操作

Gmailの通知をよく見てみると、「ボタン」が表示されていて、ショートカット操作がとても便利だった。

なので、それを真似して、以下のように、通知に「ボタン」を表示してみよう。

Screenshot_2017-11-13-00-45-15.png

サンプルコード

addAction」を実装するという、シンプルな対応で実現が可能だ。

Notification.Actionは、

・ボタンのアイコン
・ボタンのラベルテキスト
・ボタン押下時に送信するPendingIntent

を設定するだけでOK。

おぉ、必要最低限、分かりやすいね。

        Intent intent = new Intent();
        intent.setAction(ACTION_NOTIFICATION_OFF);
        intent.putExtra(EXTRA_NOTIFICATION_ID, _id);

        Notification.Action action =
                new Notification.Action(
                        R.drawable.ic_notifications_off,
                        getString(R.string.notification_off),
                        PendingIntent.getBroadcast(
                                context, (int) _id, intent, PendingIntent.FLAG_UPDATE_CURRENT)
                );

        Notification.Builder builder = new Notification.Builder(context);
        builder.addAction(action);

ちなみに、「setActions」を用いることによって、ボタンは複数を表示することが可能だ。

また、ボタンのアイコンは、以下の記事と同じ概念で、

【Android】Toolbarのアイコンサイズは「24dp」(「32dp」ではない)!

「System icon」として「24dp」を選択すれば、デザインは問題ない。

アイコンの色は、システムによって色を設定されるので、意識しなくていい。

サンプルアプリ

自分としては、プロジェクト一式や操作動画を眺めるよりも、アプリの実動作・見栄えを自らの手で確認したいと思うことの方が圧倒的に多く、それがやっぱり開発では大事なので、良ければ、同じ思いだという方は、以下のアプリ(=文中のスクショのアプリ)を参考にどうぞ。

ic_launcher.png
シンプルなメモ帳はロック画面にも通知する-簡単操作とマテリアルデザインの無料ノート-MEMOBOSS

【動作環境】
Android OS 5.0以上

Made in Japan.
© CUTBOSS
Producer & Director, Boss of the Barber.
Lead Programmer & Designer, Boss of the Barber.

6
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
11