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

Androidで通知にバイブレーションとサウンドを追加する方法【コード例付き】

Androidで通知にバイブレーションとサウンドを追加する方法

このチュートリアルでは、Androidアプリの通知にバイブレーション(振動)と通知音を追加する方法を、実際のコード例とともに解説します。NotificationCompat.BuilderのsetVibrate()メソッドとsetSound()メソッドを使えば、ユーザーの目にも耳にも届きやすい通知を簡単に実装できます。

ステップ1:新しいプロジェクトを作成する

まず、Android Studioで新しいプロジェクトを作成しましょう。「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成します。

ステップ2:res/layout/activity_main.xmlにコードを追加する

次に、レイアウトファイルに以下のコードを追加します。ここでは、画面中央に「Create notification(通知を作成)」というボタンを1つ配置しています。

<? xml version= "1.0" encoding= "utf-8" ?>
<android.support.constraint.ConstraintLayout
   xmlns: android = "https://schemas.android.com/apk/res/android"
   xmlns: app = "https://schemas.android.com/apk/res-auto"
   xmlns: tools = "https://schemas.android.com/tools"
   android :layout_width= "match_parent"
   android :layout_height= "match_parent"
   android :padding= "16dp"
   tools :context= ".MainActivity" >
   <Button
      android :id= "@+id/btnCreateNotification"
      android :layout_width= "0dp"
      android :layout_height= "wrap_content"
      android :text= "Create notification"
      app :layout_constraintBottom_toBottomOf= "parent"
      app :layout_constraintEnd_toEndOf= "parent"
      app :layout_constraintStart_toStartOf= "parent"
      app :layout_constraintTop_toTopOf= "parent" />
</android.support.constraint.ConstraintLayout>

ステップ3:src/MainActivity.javaにコードを追加する

続いて、メインのアクティビティに以下のコードを追加します。ボタンがタップされると、RingtoneManager.getDefaultUri()でシステムのデフォルト通知音を取得し、setVibrate()で振動パターン(1秒振動→1秒休止を繰り返すパターン)、setSound()で通知音をそれぞれ設定したうえで通知を発行します。

package app.tutorialspoint.com.notifyme;
import android.app.NotificationManager;
import android.content.Context;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
   private final static String default_notification_channel_id = "default" ;
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState);
      setContentView(R.layout. activity_main );
      Button btnCreateNotification = findViewById(R.id. btnCreateNotification );
      btnCreateNotification.setOnClickListener( new View.OnClickListener() {
         @Override
         public void onClick (View v) {
            Uri alarmSound = RingtoneManager. getDefaultUri (RingtoneManager. TYPE_NOTIFICATION);
            NotificationCompat.Builder mBuilder =
               new NotificationCompat.Builder(MainActivity.this,
               default_notification_channel_id )
               .setSmallIcon(R.drawable. ic_launcher_foreground )
               .setVibrate( new long []{ 1000 , 1000 , 1000 , 1000 , 1000 })
               .setContentTitle( "Test" )
               .setSound(alarmSound)
               .setContentText( "Hello! This is my first push notification" ) ;
            NotificationManager mNotificationManager = (NotificationManager)
               getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(( int ) System. currentTimeMillis (), mBuilder.build());
         }
      });
   }
}

ステップ4:AndroidManifest.xmlにコードを追加する

最後に、マニフェストファイルに以下のコードを追加します。バイブレーション機能を使用するためには、android.permission.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>
      <service
         android :name= ".MyFirebaseMessagingService"
         android :exported= "false" >
         <intent-filter>
            <action android :name= "com.google.firebase.MESSAGING_EVENT" />
         </intent-filter>
      </service>
   </application>
</manifest>

アプリを実行して動作を確認しよう

それでは、アプリを実行してみましょう。ここでは、実際のAndroid端末をパソコンに接続していることを前提としています。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。実行デバイスとして自分のモバイル端末を選択すると、端末に以下のような初期画面が表示されます。

Androidで通知にバイブレーションとサウンドを追加する方法【コード例付き】

画面上の「Create notification」ボタンをタップすれば、設定した振動パターンと通知音とともに通知が表示されるはずです。これで、Androidアプリの通知にバイブレーションとサウンドを組み込む基本的な実装は完了です。

  1. AndroidスマートフォンのPowerPointに写真や動画を追加する方法

    Microsoft PowerPointはAndroid向けにもアプリが提供されています。デスクトップ版ほど高機能ではありませんが、パソコンから離れた場所で基本的な作業を行いたい方にとっては十分な性能を持っています。PowerPointで最もよく行われる作業のひとつが、既存または新規作成したプレゼンテーションに音声や動画を挿入することです。デスクトップ環境では頻繁に行われる操作ですが、パソコンのそばにいないときはどうすればよいのでしょうか?そこで活躍するのがAndroid版PowerPointです。このアプリを使えば、文書への音声や動画の追加も比較的簡単に行えます。音声や動画ファイルを挿入する

  2. 【Android】Snapchatの通知音を変更する4つの方法を徹底解説

    Snapchatは、Z世代を中心に絶大な人気を誇るSNSアプリです。カメラ撮影や写真フィルター、音声通話、ビデオ通話、チャットといった多彩な機能をひとつのアプリで完結できることから、「オールインワン」と呼ばれるほど多くのユーザーに愛用されています。さらに「スナップストリーク(Streak)」機能を利用すれば、毎日写真や動画を送り合うことで友だちとのつながりを楽しく維持できます。ただし、スナップが届くたびに通知バーから音が鳴るため、ストリークを続けている方の中には「通知音が何度も鳴って気になる」「デフォルトの音に飽きた」と感じている方も多いのではないでしょうか。そこで本記事では、Androidス