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

【Android】ステータスバーにアイコンを表示せずに通知を作成する方法

はじめに

このチュートリアルでは、ステータスバーにアイコンを表示させずにAndroidで通知を作成する方法を、サンプルコードとともに解説します。ポイントはRemoteViewsによるカスタムレイアウトの適用と、setVisibility()VISIBILITY_SECRETを指定することです。

手順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:カスタム通知レイアウトの作成

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">
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Testing"
        android:textColor="#000"
        android:textSize="18sp" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_marginTop="8dp"
        android:hint="We are testing without icon"
        android:inputType="text"
        android:textSize="14sp" />
</RelativeLayout>

手順4:MainActivity.javaの編集

src/MainActivity.javaに以下のコードを追加します。ここでの重要なポイントは次の2点です。

  • RemoteViews: 手順3で作成したカスタムレイアウトを、通知のコンテンツとして設定します。
  • VISIBILITY_SECRET: setVisibility()に指定することで、通知の公開範囲を最も限定した状態にします。ロック画面などへの露出が抑えられます。
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);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }
        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
    }
}

なお、上記のコードは旧supportライブラリを使用しています。AndroidXを採用している新規プロジェクトの場合は、import文をandroidx.appcompat.app.AppCompatActivityおよびandroidx.core.app.NotificationCompatに読み替えてください。

手順5: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のステータスバーや通知領域に表示される、見慣れないアイコンに戸惑ったことはありませんか?ご安心ください。本記事では、Android端末に表示されるさまざまなアイコンの意味をわかりやすく解説します。ステータスバーと通知バーは別物!その違いとはAndroidのステータスバーは、いわば端末のための「掲示板」のような存在です。受信した新着メッセージや、Instagramでのいいね、ライブ配信の開始など、日常のあらゆる出来事を知らせてくれます。ただし、通知が溜まり続けると画面が雑然として見づらくなるため、こまめに整理するのがおすすめです。多くの人はステータスバーと通知バーを同じものと思いが

  2. Androidのステータスバーと通知バーをカスタマイズする方法|手動設定からおすすめアプリ6選まで

    Androidは、これまでに設計された中でも最もカスタマイズ性の高いOSの一つです。他のモバイルOSと比べて、自由度の高いパーソナライズ機能が提供されています。Google Playストアで「カスタマイズ」と検索すれば、ランチャーアプリ、アイコンパック、Androidテーマ、ライブ壁紙、通知バーやステータスバーのカスタマイズアプリなど、数百ものアプリがさまざまなカテゴリで表示されます。 正直なところ、ランチャーアプリを使えばスマートフォンの見た目や操作感は大きく変わります。しかし、通知センターやステータスバーといった要素までは変更できません。そこで活躍するのが、専用のカスタマイズアプリです。