Android Notification(通知) サンプル

notification

開始したサービスから、通知を行い、通知をクリックしたら Activity を表示する。

https://github.com/pppiroto/KaigiUtil/tree/73bfa6c6a624207552066129b157353b159f2ca5

1.通知アイコン

通知アイコンを準備。

AndroidStudio から、res/drawable のコンテキストメニューから、New-Image Asset を選択、Icon Type に、Notification icons を指定

notification_icon

2.Notificationの作成

https://developer.android.com/guide/topics/ui/notifiers/notifications.html?hl=ja

package info.typea.kaigiutil;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.widget.Toast;

public class SleepDefenderService extends Service {
    private Vibrator vibrator;

    public SleepDefenderService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        vibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);
        if (!vibrator.hasVibrator()) {
            Toast.makeText(this, "no vibrator.", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "start vibe as service", Toast.LENGTH_SHORT).show();
            long pattern[] = {1000, 100};
            int repeatIndex = 0; // 繰り返し開始位置 -1の場合繰り返しなし
            vibrator.vibrate(pattern, repeatIndex);
        }

        doNnotify();

        return START_STICKY;
    }

    /**
     * notifications
     */
    private void doNnotify(){
        // 通知を作成
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("Kaigi Util")
                .setContentText("Stop sleep defender for click here.")
                .setTicker("Sleep defender started.");

        // Activity を起動
        Intent resultIntent = new Intent(this, ContentActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(ContentActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent pendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        builder.setContentIntent(pendingIntent);

        int notificationId = 1;

        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        manager.notify(notificationId, builder.build());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        vibrator.cancel();
        Toast.makeText(this, "stop vibe as service", Toast.LENGTH_SHORT).show();
    }
}