Android
 Computer >> コンピューター >  >> プログラミング >> Android

Androidアプリでプッシュ通知受信時に新しい通知を追加する方法

このチュートリアルでは、Androidアプリでプッシュ通知を受信した際に、新たな通知を追加して表示する方法を、サンプルコードとともにわかりやすく解説します。通知チャンネルの作成方法や、通知ごとに一意のIDを割り当てるテクニックなど、実装時に押さえておきたいポイントもあわせて紹介します。

ステップ1:新規プロジェクトの作成

Android Studioを起動し、メニューから「File」⇒「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。

ステップ2:レイアウトファイル(activity_main.xml)の編集

res/layout/activity_main.xml に以下のコードを追加します。ここでは、タップすると通知を生成するボタンを画面中央に配置しています。

<? 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"
   tools :context = ".MainActivity" >
   <Button
      android :onClick = "createNotification"
      android :layout_width = "match_parent"
      android :layout_height = "wrap_content"
      android :layout_centerInParent = "true"
      android :layout_margin = "16dp"
      android :text = "Create notification" />
</RelativeLayout>

ステップ3:MainActivity.java の編集

src/MainActivity.java に以下のコードを追加します。ボタンがクリックされると createNotification() メソッドが呼び出され、通知が作成される仕組みです。Android 8.0(APIレベル26)以降では通知チャンネルが必須となるため、OSバージョンを判定してチャンネルを作成しています。また、notify() メソッドに System.currentTimeMillis() を渡すことで、通知ごとに一意のIDを割り当てており、これにより複数の通知が上書きされずに個別の通知として追加されます。

package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.Toast ;
public class MainActivity extends AppCompatActivity {
   public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
   private final static String default_notification_channel_id = "default" ;
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
      onNewIntent(getIntent()) ;
   }
   public void createNotification (View view) {
      NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;
      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
      mBuilder.setContentTitle( "Notify Me" ) ;
      mBuilder.setContentText( "Something important!" ) ;
      mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
      mBuilder.setAutoCancel( true ) ;
      if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
         int importance = NotificationManager. IMPORTANCE_HIGH ;
         NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
         mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
         assert mNotificationManager != null;
         mNotificationManager.createNotificationChannel(notificationChannel) ;
      }
      assert mNotificationManager != null;
      mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
   }
}

ステップ4:AndroidManifest.xml の編集

AndroidManifest.xml に以下のコードを追加します。振動による通知を行うため、VIBRATE パーミッションを宣言している点に注目してください。

<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "https://schemas.android.com/apk/res/android"
   package = "app.tutorialspoint.com.notifyme" >
   <uses-permission android :name = "android.permission.VIBRATE" />
   <application
      android :allowBackup = "true"
      android :icon = "@mipmap/ic_launcher"
      android :label = "@string/app_name"
      android :roundIcon = "@mipmap/ic_launcher_round"
      android :supportsRtl = "true"
      android :theme= "@style/AppTheme" >
      <activity android :name = ".MainActivity" >
         <intent-filter>
            <action android :name = "android.intent.action.MAIN" />
            <category android :name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

アプリの実行と動作確認

それでは、アプリケーションを実行してみましょう。ここでは、実際のAndroid端末をパソコンに接続しているものとします。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。選択肢として自分のモバイルデバイスを選ぶと、端末にデフォルト画面が表示されます。「Create notification」ボタンをタップするたびに、新しい通知が通知領域に次々と追加されていくことを確認できます。

  1. Androidアプリでカレンダーイベントを追加する方法【サンプルコード付きで解説】

    はじめに このチュートリアルでは、Androidアプリから端末のカレンダーにイベントを追加する方法を、ステップごとにわかりやすく解説します。Intent(インテント)を利用することで、標準のカレンダーアプリのイベント編集画面をそのまま呼び出せるため、複雑な権限処理を書かずに簡単に実装できるのが大きな特徴です。 手順1:Android Studioで新規プロジェクトを作成 まずはAndroid Studioで新しいプロジェクトを作成しましょう。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを生成します。 手順2:レイアウトファイル(activ

  2. Android StudioでJARファイルをライブラリとして追加する方法を徹底解説

    この記事では、Android StudioでJARファイルをライブラリとして追加する手順を、初心者の方にもわかりやすいようにステップごとに解説します。外部ライブラリ(JAR)を活用すれば、既存のコード資産を再利用でき、開発効率が大きく向上します。ステップ1:新規プロジェクトを作成するまず、Android Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。プロジェクト名やパッケージ名など、必要な項目をすべて入力して進みましょう。ステップ2:JARファイルをlibsフォルダに配置する次に、使用したいJARファイルをProject/a