【Android Studio】Javaで通知する方法
Android StudioのJavaを使って通知を送る方法を説明していきたいと思います。どのAPIレベルにまで対応しているかわかりませんがAPIレベル28では実行することができました。
AndroidManifestの設定
今回はAndroidManifestに入力するコードはありませんので入力しないで大丈夫です。
layoutの設定
次にlayoutに入力するコードです。上から2行目にある「androidx.constraintlayout.widget.ConstraintLayout」だけ消去して代わりに「LinearLayout」を入力します。
「tools:context=".MainActivity"」と「>」の間で改行し、「android:orientation="vertical"」を入力してください。
「TextView~/>」は使わないので消去し、代わりにこちらを入力してください。
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON"
android:textSize="42sp" />
Javaの設定
最後にメインであるJavaに入力するコードです。入力してもらいたい場所が2か所あります。
「setContentView(R.layout.activity_main);」の下に書いてください。
findViewById(R.id.button1).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
createNotificationChannel();
}
}
);
「createNotificationChannel」を呼び出しています。
「protected void onCreate(Bundle savedInstanceState) {}」の外に書いてください。
private void createNotificationChannel() {
String channelId = "CHANNEL_ID";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
builder.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("name1")
.setContentText("description1")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String name = "name2";
String description = "description2";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
final int notify_id = 123456;
NotificationManagerCompat.from(this)
.notify(notify_id, builder.build());
}
「name1」にタイトルを、「description1」に内容を入力してください。
実行すると「NO」ボタンが表示されます。押すとアラームが鳴り、上に「-」が表示されるので押してみると通知の内容が見ることができます。
まとめ
今回は、通知する方法を説明していきました。私も作り直しながら説明していったのでエラーや、入力ミスはないようにできていると思います。この方法で取得できなかった場合はコメントください。できる限り対処していきたいと思います。
アプリ開発は調べることがほとんどです。私はこのプログラムを作るまでにたくさんのサイトを見て回ることになってしまいました。皆さんには同じ思いをしてほしくないのでこのプログラムが役に立つことを祈っています。