我正在创建两个应用程序-第一个发送广播,第二个应该获取广播。
发送以下信息的应用程序:
清单中声明的权限:
<permission-group
android:name="com.example.smbmp1.permissions"
android:label="my permissions group"/>
<permission
android:name="com.example.smbmp1.permissions.PRODUCT_BROADCAST_PERMISSION"
android:label="PRODUCT_BROADCAST_PERMISSION"
android:permissionGroup="com.example.smbmp1.permissions"/>
<uses-permission android:name="com.example.smbmp1.permissions.PRODUCT_BROADCAST_PERMISSION"/>
负责发送的代码片段:
private fun populateProduct(product: Product) {
Intent().also { intent ->
intent.action = "com.example.smbmp1.PRODUCT_BROADCAST"
intent.putExtra("id", product.id)
intent.putExtra("name", product.name)
intent.putExtra("price", product.price)
intent.putExtra("quantity", product.quantity)
sendBroadcast(intent, Manifest.permission.PRODUCT_BROADCAST_PERMISSION)
}
}
接收以下内容的应用程序:
注册接收者:
<receiver
android:name=".ProductReceiver"
android:enabled="true"
android:exported="true"
android:process=":remote"
android:permission="com.example.smbmp1.permissions.PRODUCT_BROADCAST_PERMISSION">
<intent-filter >
<action android:name="com.example.smbmp1.PRODUCT_BROADCAST" />
</intent-filter>
</receiver>
也声明了权限清单(我也在尝试在第二个应用中未声明):
<permission-group
android:name="com.example.smbmp1.permissions"
android:label="my permissions group"/>
<permission
android:name="com.example.smbmp1.permissions.PRODUCT_BROADCAST_PERMISSION"
android:label="PRODUCT_BROADCAST_PERMISSION"
android:permissionGroup="com.example.smbmp1.permissions"/>
<uses-permission android:name="com.example.smbmp1.permissions.PRODUCT_BROADCAST_PERMISSION"/>
简单的接收方代码:
package com.example.smbmp2
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
class ProductReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "Receiver", Toast.LENGTH_LONG).show()
}
}
问题是,没有触发接收器。我经历了所有堆栈溢出问题,但所有答案都无济于事。我试图将类别设置为意图,设置标志等。
有什么建议吗?
编辑
我也尝试过动态注册广播接收器:
package com.example.smbmp2
import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
private lateinit var productReceiver: ProductReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onStart() {
super.onStart()
productReceiver = ProductReceiver()
registerReceiver(productReceiver, IntentFilter("com.example.smbmp1.PRODUCT_BROADCAST"), Manifest.permission.PRODUCT_BROADCAST_PERMISSION, null)
}
override fun onStop() {
super.onStop()
unregisterReceiver(productReceiver)
}
}
答案 0 :(得分:0)
尝试一下? https://stackoverflow.com/a/33611355/9392134
您忘记了使用软件包和BroadCast Receiver类来设置ComponentName。
答案 1 :(得分:0)
我已经解决了问题。首先,我将动态注册从onStart方法移至onCreate方法,并将取消注册从onStop移至onDestroy。之后,我升级了android studio,就解决了这个问题。