techium

このブログは何かに追われないと頑張れない人たちが週一更新をノルマに技術情報を発信するブログです。もし何か調査して欲しい内容がありましたら、@kobashinG or @muchiki0226 までいただけますと気が向いたら調査するかもしれません。

Android で UILocalNotification

Android で UILocalNotification

概要

指定時間に指定した内容を通知バーに表示する機能を Android で実現する。
調べたところそのような機能は Android SDK 標準には無いようなので、

  • 指定時間に処理を実行
  • ステータスバーに通知表示

という2機能を実装し、繋げることで同機能を実現する。

指定時間に処理を実行

指定時間に処理を実行するには AlarmManager を使用する。

    GregorianCalendar calendar = new GregorianCalendar(mYear,mMonth,mDay,mHour,mMinute); // 時間を指定する

    Intent resultIntent = new Intent(getApplicationContext(), AlarmReceiver.class); // 指定時刻にアラームを受けるクラスを指定

    PendingIntent resultPendingIntent = PendingIntent.getBroadcast(
        this,
        mId, // この ID を使用すれば後でアラームをキャンセルしたり上書きしたりできる。
        resultIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
    );

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), resultPendingIntent);

アラームを受けるクラスは以下のように、BroadcastReceiver を継承して作成する。

public class AlarmReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    // アラームを受けた際の処理を実装
  }
}

ステータスバーに通知表示

通知の表示には NotificationManager を使用する。

    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.notification_template_icon_bg)
        .setTicker(task.getTitle())
        .setWhen(System.currentTimeMillis())
        .setContentTitle(task.getTitle())
        .setContentText(task.getContents())
        .setDefaults(Notification.DEFAULT_ALL)
        .build();

    notificationManager.cancelAll(); // 前に出した通知を消す
    notificationManager.notify(R.string.app_name, notification);

これを先述の onReceive 内に記載すれば、指定時間に通知を表示するという UILocalNotification ぽいものが実装できる。

その他

通知領域タップ時の挙動も UILocalNotification ぽくしたい。

自アプリの、最後にアクティブだった Activity を、再生成することなくそのまま Foreground に持ってくる、というようなことができればいいのか。

この辺りは要調査。