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

【Android開発】通知のバイブレーションとライトを有効にする方法を徹底解説

この記事では、Androidの通知でバイブレーション(振動)とライト(通知LED)を有効にする方法を、サンプルコード付きで段階的に解説します。Android 8.0(API レベル26)以降では、通知チャンネル(NotificationChannel)経由でこれらの設定を行う必要があるため、その実装手順もあわせて紹介します。

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

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

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

res/layout/activity_main.xml に以下のコードを追加します。画面中央に「Create notification」ボタンを配置したシンプルなレイアウトです。

<?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:custom_notification_layout.xml にコードを追加する

次に、カスタム通知用のレイアウトファイル res/layout/custom_notification_layout.xml を作成し、以下のコードを記述します。アイコン・タイトル・テキスト入力欄を持つカスタムビューを定義しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="96dp"
    android:padding="10dp">
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentStart="true"
        android:layout_marginEnd="10dp"
        android:contentDescription="@string/app_name"
        android:src="@mipmap/ic_launcher"/>
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/image"
        android:text="Testing"
        android:textColor="#000"
        android:textSize="18sp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_marginTop="8dp"
        android:layout_toEndOf="@+id/image"
        android:hint="Enter something..."
        android:inputType="text"
        android:textSize="14sp"/>
</RelativeLayout>

ステップ4:MainActivity にコードを追加する

src/MainActivity.java に以下のコードを追加します。
重要なポイント:Android 8.0(API 26)以降では、NotificationChannel を作成し、setLightColor() で通知ライトの色を、setVibrationPattern()enableVibration(true) で振動パターンをそれぞれ指定します。

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.RemoteViews;
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) {
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
        mBuilder.setContent(contentView);
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_SECRET);
        long[] VIBRATE_PATTERN = {0, 500};
        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);
            notificationChannel.setLightColor(R.color.colorAccent);
            notificationChannel.setVibrationPattern(VIBRATE_PATTERN);
            notificationChannel.enableVibration(true);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }
        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
    }
}

補足:振動パターンは long 型の配列で指定します。たとえば {0, 500} の場合、「即座に開始して500ミリ秒間振動する」という意味になります。配列の要素数を増やせば、振動と停止を交互に繰り返す複雑なパターンも作成できます。

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

最後に、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>
    </application>
</manifest>

アプリを実行して動作を確認する

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

「Create notification」ボタンをタップすると、指定した振動パターンで端末が振動し、通知LEDがアクセントカラーで点灯します。これで、通知のバイブレーションとライトの有効化は完了です。

【Android開発】通知のバイブレーションとライトを有効にする方法を徹底解説

  1. Android 9/10対応UI/UX設計ガイド:Material Designの基本と実践テクニック

    Googleは2019年9月に最新OS「Android 10」をリリースしました。現時点では一部の最新ハイエンド端末にのみ搭載されていますが、今後、各メーカーが比較的新しいモデルへ順次展開していくことが予想されています。Android 10では、システム全体に適用されるダークモードをはじめ、数々の便利な新機能が追加されました。一方で、UI自体の大きな刷新はほとんど行われませんでした。GoogleはMaterial Design(マテリアルデザイン)が極めて高い完成度を持つため、これを引き続き採用しています。そのため、本ガイドで紹介する内容は、OreoやPieなど以前のAndroidバージョンに

  2. Androidでプッシュ通知を有効にする方法【初心者向け完全ガイド】

    プッシュ通知とは、スマートフォンの画面に随時ポップアップ表示されるメッセージのことです。ネットショッピングが好きな方にとって、プッシュ通知はお得なキャンペーンやセール情報をいち早く知らせてくれる便利な機能です。中には数時間限定の特別オファーなども含まれているため、見逃せない情報も多いでしょう。しかし、うっかりAndroidでプッシュ通知を無効にしてしまうと、大切なお知らせを受け取れなくなってしまいます。そこで本記事では、プッシュ通知を再度有効にする手順をわかりやすく解説します。アプリはインストール時に通知許可を求めてくるほとんどのアプリは、インストール時にプッシュ通知の送信許可を求めるダイアロ