Android-notifications

提供:Dev Guides
移動先:案内検索

Android-通知

'_*通知*は、アプリケーションの通常のUI以外でユーザーに表示できるメッセージです。 システムに通知を発行するように指示すると、最初に通知領域にアイコンとして表示されます。 通知の詳細を表示するには、ユーザーは通知ドロワーを開きます。 通知領域と通知ドロワーはどちらも、ユーザーがいつでも表示できるシステム制御の領域です。_

Android Toast クラスはユーザーにアラートを表示する便利な方法を提供しますが、問題はこれらのアラートが永続的ではないことです。つまり、画面上でアラートが数秒間点滅して消えます。

Android通知バー

通知の詳細を表示するには、通知に関する詳細を含む通知ドロワーを表示するアイコンを選択する必要があります。 仮想デバイスでエミュレーターを使用しているときに、ステータスバーをクリックして下にドラッグして展開し、次のように詳細を表示する必要があります。 これはちょうど 64 dp の高さで、通常ビューと呼ばれます。

Android通知の詳細

上記の拡張フォームには、通知に関する追加の詳細が表示される*ビッグビュー*を含めることができます。 通知には最大6行を追加できます。 次のスクリーンショットは、そのような通知を示しています。

通知を作成して送信する

通知を作成する簡単な方法があります。 アプリケーションで次の手順に従って、通知を作成します-

ステップ1-通知ビルダーを作成する

最初のステップは、_NotificationCompat.Builder.build()_を使用して通知ビルダーを作成することです。 Notification Builderを使用して、小さいアイコンや大きいアイコン、タイトル、優先度などのさまざまな通知プロパティを設定します。

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

手順2-通知プロパティの設定

*Builder* オブジェクトを取得したら、要件に従ってBuilderオブジェクトを使用してその通知プロパティを設定できます。 しかし、これは少なくとも以下を設定することが必須です-
  • * setSmallIcon()*で設定された小さなアイコン
  • * setContentTitle()*で設定されたタイトル
  • 詳細テキスト、* setContentText()*で設定
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");

通知用に設定できるオプションのプロパティがたくさんあります。 それらの詳細については、NotificationCompat.Builderのリファレンスドキュメントを参照してください。

ステップ3-アクションの添付

これはオプションの部分であり、通知にアクションを添付する場合に必要です。 アクションを使用すると、ユーザーは通知からアプリケーションの*アクティビティ*に直接移動し、1つ以上のイベントを確認したり、さらに作業を行うことができます。

アクションは、アプリケーションでアクティビティを開始する Intent を含む PendingIntent によって定義されます。 PendingIntentをジェスチャーに関連付けるには、_NotificationCompat.Builder_の適切なメソッドを呼び出します。 たとえば、ユーザーが通知ドロワーで通知テキストをクリックしたときにアクティビティを開始する場合は、* setContentIntent()*を呼び出してPendingIntentを追加します。

PendingIntentオブジェクトを使用すると、アプリケーションが実行されているかどうかを気にせずに、多くの場合、後でアプリケーションに代わってアクションを実行できます。

開始されたアクティビティの人工的なバックスタックを含むスタックビルダーオブジェクトを利用します。 これにより、アクティビティから逆方向にナビゲートすると、アプリケーションからホーム画面に移動できます。

Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);

//Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

ステップ4-通知を発行する

最後に、NotificationManager.notify()を呼び出して通知を送信することにより、Notificationオブジェクトをシステムに渡します。 通知する前に、Builderオブジェクトで* NotificationCompat.Builder.build()メソッドを必ず呼び出してください。 このメソッドは、設定されているすべてのオプションを組み合わせて、新しい *Notification オブジェクトを返します。

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());

NotificationCompat.Builderクラス

NotificationCompat.Builderクラスを使用すると、すべてのフラグを簡単に制御できるだけでなく、一般的な通知レイアウトを構築できます。 以下は、NotificationCompat.Builderクラスの一部として使用できる、いくつかの重要で最も頻繁に使用されるメソッドです。

Sr.No. Constants & Description
1

Notification build()

設定されているすべてのオプションを組み合わせて、新しい通知オブジェクトを返します。

2

NotificationCompat.Builder setAutoCancel (boolean autoCancel)

このフラグを設定すると、ユーザーがパネルで通知をクリックしたときに通知が自動的にキャンセルされます。

3

NotificationCompat.Builder setContent (RemoteViews views)

標準のものの代わりに使用するカスタムRemoteViewsを提供します。

4

NotificationCompat.Builder setContentInfo (CharSequence info)

通知の右側に大きなテキストを設定します。

5

NotificationCompat.Builder setContentIntent (PendingIntent intent)

通知がクリックされたときに送信するPendingIntentを指定します。

6

NotificationCompat.Builder setContentText (CharSequence text)

標準通知で、通知のテキスト(2行目)を設定します。

7

NotificationCompat.Builder setContentTitle (CharSequence title)

標準通知で、通知のテキスト(最初の行)を設定します。

8

NotificationCompat.Builder setDefaults (int defaults)

使用されるデフォルトの通知オプションを設定します。

9

NotificationCompat.Builder setLargeIcon (Bitmap icon)

ティッカーと通知に表示される大きなアイコンを設定します。

10

NotificationCompat.Builder setNumber (int number)

通知の右側に大きな数字を設定します。

11

NotificationCompat.Builder setOngoing (boolean ongoing)

これが継続的な通知かどうかを設定します。

12

NotificationCompat.Builder setSmallIcon (int icon)

通知レイアウトで使用する小さなアイコンを設定します。

13

NotificationCompat.Builder setStyle (NotificationCompat.Style style)

ビルド時に適用される豊富な通知スタイルを追加します。

14

NotificationCompat.Builder setTicker (CharSequence tickerText)

通知が最初に到着したときにステータスバーに表示されるテキストを設定します。

15

NotificationCompat.Builder setVibrate (long[] pattern)

使用する振動パターンを設定します。

16

NotificationCompat.Builder setWhen (long when)

イベントが発生した時刻を設定します。 パネル内の通知は、この時間でソートされます。

次の例は、Android 4.1で導入された NotificationCompat.Builder クラスを使用したAndroid通知の機能を示しています。

Step Description
1 You will use Android studio IDE to create an Android application and name it as finddevguides under a package com.example.notificationdemo.
2 Modify src/MainActivity.java file and add the code to notify(""), if user click on the button,it will call android notification service.
3 Create a new Java file src/NotificationView.java, which will be used to display new layout as a part of new activity which will be started when user will click any of the notifications
4 Modify layout XML file res/layout/activity_main.xml to add Notification button in relative layout.
5 Create a new layout XML file res/layout/notification.xml. This will be used as layout file for new activity which will start when user will click any of the notifications.
6 No need to change default string constants. Android studio takes care of default string constants
7 Run the application to launch Android emulator and verify the result of the changes done in the application.

以下は、変更されたメインアクティビティファイル src/com.example.notificationdemo/MainActivity.java の内容です。 このファイルには、基本的な各ライフサイクルメソッドを含めることができます。

package com.example.notificationdemo;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
   Button b1;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      b1 = (Button)findViewById(R.id.button);
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            addNotification();
         }
      });
   }

   private void addNotification() {
      NotificationCompat.Builder builder =
         new NotificationCompat.Builder(this)
         .setSmallIcon(R.drawable.abc)
         .setContentTitle("Notifications Example")
         .setContentText("This is a test notification");

      Intent notificationIntent = new Intent(this, MainActivity.class);
      PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
         PendingIntent.FLAG_UPDATE_CURRENT);
      builder.setContentIntent(contentIntent);

     //Add as notification
      NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      manager.notify(0, builder.build());
   }
}

以下は res/layout/notification.xml ファイルの内容です-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent" >

   <TextView
      android:layout_width="fill_parent"
      android:layout_height="400dp"
      android:text="Hi, Your Detailed notification view goes here...."/>
</LinearLayout>

以下は、変更されたメインアクティビティファイル src/com.example.notificationdemo/NotificationView.java の内容です。

package com.example.notificationdemo;

import android.os.Bundle;
import android.app.Activity;

public class NotificationView extends Activity{
   @Override
   public void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.notification);
   }
}

以下は res/layout/activity_main.xml ファイルの内容です-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://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="MainActivity">

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Notification Example"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"/>

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_below="@+id/textView1"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="48dp"/>

   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="42dp"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Notification"
      android:id="@+id/button"
      android:layout_marginTop="62dp"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true"/>

</RelativeLayout>

以下は、2つの新しい定数を定義する res/values/strings.xml の内容です-

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="action_settings">Settings</string>
   <string name="app_name">finddevguides </string>
</resources>

以下は、 AndroidManifest.xml のデフォルトのコンテンツです-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.notificationdemo" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name="com.example.notificationdemo.MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
         </intent-filter>

      </activity>

      <activity android:name=".NotificationView"
         android:label="Details of notification"
         android:parentActivityName=".MainActivity">
         <meta-data
         android:name="android.support.PARENT_ACTIVITY"
         android:value=".MainActivity"/>
      </activity>

   </application>
</manifest>
*finddevguides* アプリケーションを実行してみましょう。 環境のセットアップ中に *AVD* を作成したと思います。 Android StudioからAPPを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[画像の実行:/android/images/eclipse_run.jpg [Eclipse Run Icon]アイコンをクリックします。 Android StudioはAVDにアプリをインストールして起動し、セットアップとアプリケーションで問題がなければ、次のエミュレータウィンドウが表示されます-

Android Notification Start

  • ボタン*をクリックすると、上部に「New Message Alert!」というメッセージが表示されます。一時的に表示され、その後、左上隅に小さなアイコンを持つ次の画面が表示されます。

次に、ビューを展開し、小さなアイコンを長押しすると、1秒後に日付情報が表示されます。これは、マウスを離さずにステータスバーを下にドラッグする時間です。 ステータスバーが展開し、次の画面が表示されます-

拡張されたAndroid通知

ビッグビュー通知

次のコードスニペットは、前のスニペットで作成された通知を変更して、受信トレイのビッグビュースタイルを使用する方法を示しています。 この機能を示すためにdisplayNotification()変更メソッドを更新します-

protected void displayNotification() {
   Log.i("Start", "notification");

  /*Invoking the default notification service*/
   NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);

   mBuilder.setContentTitle("New Message");
   mBuilder.setContentText("You've received new message.");
   mBuilder.setTicker("New Message Alert!");
   mBuilder.setSmallIcon(R.drawable.woman);

  /*Increase notification number every time a new notification arrives*/
   mBuilder.setNumber(++numMessages);

  /*Add Big View Specific Configuration*/
   NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

   String[] events = new String[6];
   events[0] = new String("This is first line....");
   events[1] = new String("This is second line...");
   events[2] = new String("This is third line...");
   events[3] = new String("This is 4th line...");
   events[4] = new String("This is 5th line...");
   events[5] = new String("This is 6th line...");

  //Sets a title for the Inbox style big view
   inboxStyle.setBigContentTitle("Big Title Details:");

  //Moves events into the big view
   for (int i=0; i < events.length; i++) {
      inboxStyle.addLine(events[i]);
   }

   mBuilder.setStyle(inboxStyle);

  /*Creates an explicit intent for an Activity in your app*/
   Intent resultIntent = new Intent(this, NotificationView.class);

   TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
   stackBuilder.addParentStack(NotificationView.class);

  /*Adds the Intent that starts the Activity to the top of the stack*/
   stackBuilder.addNextIntent(resultIntent);
   PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

   mBuilder.setContentIntent(resultPendingIntent);
   mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  /*notificationID allows you to update the notification later on.*/
   mNotificationManager.notify(notificationID, mBuilder.build());
}

これで、アプリケーションを実行しようとすると、ビューの展開された形式で次の結果が見つかります-

Android Notification Big View