MainActivity.kt
package com.example.fredric.mybroadcast import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button class MainActivity : AppCompatActivity() { var sendBroadCastBtn: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sendBroadCastBtn = findViewById<Button>(R.id.send_broadcast_btn) sendBroadCastBtn?.setOnClickListener({ _ -> var intent = Intent("com.example.broadcasttest.MY_BROADCAST") sendBroadcast(intent) }) } }
MyBroadcastReceiver.kt
package com.example.fredric.mybroadcast import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast class MyBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Toast.makeText(context,"received in my broadcast Receiver!!",Toast.LENGTH_SHORT).show() } }AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.fredric.mybroadcast"> <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> <receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.example.broadcasttest.MY_BROADCAST" /> </intent-filter> </receiver> </application> </manifest>成图效果,
评论
发表评论