Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 1 year has passed since last update.

BroadCastReceiver

Posted at

Androidプラットフォームで発生する特定のイベントやシステム通知に対応するためのコンポーネントです。BroadcastReceiverはアプリケーションがバックグラウンドで実行されている場合でも、イベントを受信して対応する処理を行うことができます。

クラスを作成

Copy code
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast

class MyReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        // 受信したブロードキャストに対する処理をここに記述
        if (intent?.action == "custom.action.MY_ACTION") {
            val message = intent.getStringExtra("message")
            Toast.makeText(context, "Received broadcast: $message", Toast.LENGTH_SHORT).show()
        }
    }
}

マニフェストに登録

<receiver android:name=".MyReceiver">
    <intent-filter>
    //ブロードキャストメッセージのアクションを一意に識別するための文字列
        <action android:name="custom.action.MY_ACTION" />
    </intent-filter>
</receiver>

アクションを飛ばす

//ブロードキャストメッセージのアクションを一意に識別するための文字列
val intent = Intent("custom.action.MY_ACTION")
//KeyとValueを
intent.putExtra("message", "Hello from sender!")

// ブロードキャストを発信
sendBroadcast(intent)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?