0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

テスト 通知設定3

Posted at

PendingIntentを使用して通知を送信し、その通知がタップされたときにブロードキャストレシーバーを継承したクラスのonReceiveメソッドを呼び出す方法は、次の手順で行えます。

  1. ブロードキャストレシーバーを継承したクラスを作成:

    まず、ブロードキャストレシーバーを継承した新しいクラスを作成します。このクラスはブロードキャストを受信する役割を担います。例えば、MyReceiverというクラスを作成しましょう。

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // ブロードキャストを受信したときの処理を記述
            String data = intent.getStringExtra("key");
            // 通知を作成または他のアクションを実行
        }
    }
    
  2. マニフェストでブロードキャストレシーバーを宣言:

    AndroidManifest.xmlファイル内で、作成したブロードキャストレシーバーを宣言します。これにより、アプリがブロードキャストを受信できるようになります。

    <receiver
        android:name=".MyReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.example.MY_ACTION" />
        </intent-filter>
    </receiver>
    

    この例では、MyReceiverクラスが "com.example.MY_ACTION" アクションを受信するように宣言されています。

  3. PendingIntentを使用して通知を送信:

    MainActivity内でPendingIntentを作成し、通知のコンテンツと一緒に設定します。通知のタップ時にブロードキャストを発信するために、PendingIntentを通知にセットします。

    Intent intent = new Intent("com.example.MY_ACTION");
    intent.putExtra("key", "value");
    
    // ペンディングインテントをブロードキャストとして作成
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
    // 通知を作成
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("通知タイトル")
            .setContentText("通知本文")
            .setContentIntent(pendingIntent) // タップ時のアクション
            .setAutoCancel(true); // 通知をタップしたら自動的に消去
    
    // 通知を表示
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notificationId, builder.build());
    

    このコードは、通知を送信するためにPendingIntentを使用し、通知がタップされたときに指定されたアクション(ブロードキャスト)を発信します。ブロードキャストはマニフェストで宣言されたMyReceiverクラスのonReceiveメソッドを呼び出します。ブロードキャストアクション名は、マニフェストで宣言したものと一致している必要があります。

これにより、通知がタップされたときにブロードキャストレシーバー内のonReceiveメソッドが呼び出され、指定したアクションに応じた処理を実行できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?