Androidの通知、PendingIntentの例

Android PendingIntentを使用したAndroid通知例へようこそ。このチュートリアルでは、PendingIntentの実装とアプリケーション内での通知の作成について説明します。

AndroidのPendingIntent

AndroidのPendingIntentは、インテントオブジェクトを包み込んだオブジェクトであり、将来的に実行されるアクションを指定します。言い換えると、PendingIntentを使用すると、将来のインテントを別のアプリケーションに渡し、そのアプリケーションが私たちのアプリケーションと同じ権限を持っているかのようにそのインテントを実行できます。私たちのアプリケーションがIntentが呼び出されるときにまだ存在しているかどうかに関係なくです。PendingIntentは通常、AlarmManagerの実行や後ほどこのチュートリアルで実装する通知の場合に使用されます。PendingIntentは、アプリケーションがプロセスが終了した後も動作する手段を提供します。セキュリティ上の理由から、PendingIntentに供給されるベースのIntentには、コンポーネント名を明示的に設定して、その地点に送信されることを確実にする必要があります。各明示的なインテントは、Activity、BroadcastReceiver、またはServiceのような特定のアプリコンポーネントによって処理されることが期待されます。したがって、PendingIntentは異なるタイプのインテントを処理するために次のメソッドを使用します。

    1. PendingIntent.getActivity():Activityを開始するためのPendingIntentを取得する

 

    1. PendingIntent.getBroadcast():ブロードキャストを実行するためのPendingIntentを取得する

 

    PendingIntent.getService():サービスを開始するためのPendingIntentを取得する

以下には、PendingIntentの使用例が示されています。

Intent intent = new Intent(this, SomeActivity.class);
 
// Creating a pending intent and wrapping our intent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
try {
    // Perform the operation associated with our pendingIntent
    pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
    e.printStackTrace();
}

PendingIntentに関連する操作は、send()メソッドを使用して実行されます。getActivity()メソッド内のパラメータとその使用方法は以下に説明されています。

    1. (文脈):これは、PendingIntentがアクティビティを開始するコンテキストです。

 

    1. requestCode:上記の例で使用される送信者のプライベートなリクエストコードは「1」です。同じメソッドで後で使用すると、同じペンディングインテントを取得できます。その後、cancel()などのさまざまな処理を行うことができます。

 

    1. intent:起動するアクティビティの明示的なインテントオブジェクト

 

    flag:上記の例で使用したPendingIntentフラグの1つはFLAG_UPDATE_CURRENTです。これにより、以前のPendingIntentが既に存在する場合、現在のインテントで更新されます。FLAG_CANCEL_CURRENTなど、他のフラグもあります。

アンドロイドの通知

AndroidのToastクラスは、ユーザーにアラートを表示する便利な方法を提供していますが、問題はこれらのアラートが一時的であるということです。つまり、アラートが画面に数秒間表示された後、消えるということです。このような場合に、Android通知メッセージが空白を埋めます。Android通知は、アプリケーションの通常のUIの外にユーザーに表示できるメッセージです。Androidの通知は、NotificationCompatライブラリを使用して構築されています。

Androidの通知を作成する

以下のように、NotificationManagerクラスを使用して通知が作成されます:

NotificationManager notificationManager = (NotificationManager) 
  getSystemService(NOTIFICATION_SERVICE); 

以下に示すように、Notification.BuilderはNotificationオブジェクトを作成するためのビルダーインターフェースを提供します。

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

アンドロイドの通知方法

このビルダーオブジェクト上で通知のプロパティを設定することができます。以下に、よく使用されるメソッドとその説明を一部示します。

    1. 通知のbuild() : 設定されたすべてのオプションを組み合わせて新しいNotificationオブジェクトを返す

NotificationCompat.Builder setAutoCancel (boolean autoCancel) : このフラグを設定すると、ユーザーがパネルでそれをクリックすると通知が自動的にキャンセルされます

NotificationCompat.Builder setContent (RemoteViews views) : 標準のものの代わりにカスタムのRemoteViewsを提供する

NotificationCompat.Builder setContentInfo (CharSequence info) : 通知の右側に表示される大きなテキストを設定する

NotificationCompat.Builder setContentIntent (PendingIntent intent) : 通知がクリックされた時に送信するPendingIntentを提供する

NotificationCompat.Builder setContentText (CharSequence text) : 通知のテキスト(2行目)を設定する

NotificationCompat.Builder setContentTitle (CharSequence title) : 通知のテキスト(1行目)を設定する

NotificationCompat.Builder setDefaults (int defaults) : 使用するデフォルトの通知オプションを設定する。例えば、mBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)

NotificationCompat.Builder setLargeIcon (Bitmap icon) : ティッカーや通知に表示される大きなアイコンを設定する

NotificationCompat.Builder setNumber (int number) : 通知の右側に表示される大きな数値を設定する

NotificationCompat.Builder setOngoing (boolean ongoing) : これが継続的な通知かどうかを設定する

NotificationCompat.Builder setSmallIcon (int icon) : 通知のレイアウトで使用する小さなアイコンを設定する

NotificationCompat.Builder setStyle (NotificationCompat.Style style) : ビルド時に適用される豊富な通知スタイルを追加する

NotificationCompat.Builder setTicker (CharSequence tickerText) : 通知が最初に到着した時にステータスバーに表示されるテキストを設定する

NotificationCompat.Builder setVibrate (long[] pattern) : 使用するバイブレーションパターンを設定する

NotificationCompat.Builder setWhen (long when) : イベントが発生した時間を設定する。パネル内の通知はこの時間でソートされる

「Androidの通知ボタンとスタイル」

Notification.Builderは、通知に定義可能な3つのアクションボタンを追加することができます。Android 4.1以降は、展開可能な通知をサポートしており、展開されると通知の大きなビューが表示されます。大きなビューには、ビッグピクチャースタイル、ビッグテキストスタイル、インボックススタイルという3つのスタイルが使用できます。

Androidの通知をキャンセルする。

NotificationManagerのcancel()メソッドを使用すると、特定の通知IDに対してもcancel()を呼び出すことができます。cancelAll()メソッドは、以前に発行したすべての通知を削除します。このチュートリアルでは、ウェブページを表示するインテントを含むアプリケーションを作成します。そのインテントは、通知がタップされたときに発火するPendingIntentとして設定されます。また、プログラムで通知をキャンセルする機能も追加します。

Android通知の例のプロジェクト構造

アンドロイドの通知の例

activity_main.xmlは、2つのボタンを持つ基本的な相対レイアウトです:1つは通知を作成し、もう1つはそれをキャンセルします。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.scdev.notifications.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CREATE NOTIFICATION"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CANCEL NOTIFICATION"
        android:id="@+id/button2"
        android:layout_below="@+id/button"
        android:layout_alignRight="@+id/button"
        android:layout_alignEnd="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

以下はMainActivity.javaです。

package com.scdev.notifications;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
    }

    @OnClick(R.id.button)
    public void sendNotification() {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.scdev.com/"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle("Notifications Title");
        builder.setContentText("Your notification content here.");
        builder.setSubText("Tap to view the website.");

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // Will display the notification in the notification bar
        notificationManager.notify(1, builder.build());
    }

    @OnClick(R.id.button2)
    public void cancelNotification() {

        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
        nMgr.cancel(1);
    }
}

上記のコードでは、このウェブサイトのインテントをPendingIntentに渡しました。notificationIdは1に設定されており、通知の構築とキャンセルに使用されます。アプリの出力結果は以下の通りです。このチュートリアルでは、Androidの通知を利用した作業を終了します。以下のリンクからAndroid通知プロジェクトをダウンロードできます。

AndroidのPendingIntentとNotifications Projectをダウンロードしてください。

参考文献:

  • https://developer.android.com/reference/android/app/PendingIntent.html
  • https://developer.android.com/guide/topics/ui/notifiers/notifications.html
コメントを残す 0

Your email address will not be published. Required fields are marked *


广告
広告は10秒後に閉じます。
bannerAds