我试图将一个基本的IntentService / BroadcastReceiver组合在一起。
是的,我知道当前没有什么用,但是我只是想让广播开始运行。
服务收到了我的初衷,但是接收方没有得到返回的广播(调试器)。其他答案并没有帮助我,我觉得我已经尝试了一切。它一定是微不足道的,但我只是不能将其放在上面。
显示 Activity :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val filter = IntentFilter()
filter.addAction(Constants.BROADCAST_ACTION)
filter.addDataScheme("http")
val dsl = DownloadStateReceiver()
LocalBroadcastManager.getInstance(this).registerReceiver(dsl,filter)
buttonLogin.setOnClickListener({
var loginIntent = Intent(this,RawRestJsonPull::class.java)
loginIntent.putExtra("userName",editLogin.text.toString())
loginIntent.putExtra("password",editPassword.text.toString())
this.startService(loginIntent)
})
}
class DownloadStateReceiver : BroadcastReceiver()
{
override fun onReceive(currentContext: Context, incomingIntent: Intent) {
Log.d("?????","d")
}
}
}
服务和 Action 常量:
class RawRestJsonPull : IntentService("rest" ) {
override fun onHandleIntent(incomingIntent: Intent) {
var outgoingIntent = Intent(Constants.BROADCAST_ACTION)
var status = 0
var userName : String? = incomingIntent.getStringExtra("userName")
var password : String? = incomingIntent.getStringExtra("password")
outgoingIntent.putExtra(Constants.EXTENDED_DATA_STATUS,status).putExtra("userName",userName).
putExtra("password",password)
outgoingIntent.flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES
LocalBroadcastManager.getInstance(this).sendBroadcast(outgoingIntent)
}
}
class Constants
{
companion object {
val BROADCAST_ACTION = "com.example.hubert1224.xxx.BROADCAST"
val EXTENDED_DATA_STATUS = "com.example.hubert1224.xxx.STATUS"
}
}
表现:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hubert1224.xxx">
<uses-permission android:name="android.permission.INTERNET" />
<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"
android:windowSoftInputMode="stateVisible">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".RawRestJsonPull" />
<receiver android:name=".MainActivity$DownloadStateReceiver" />
</application>
</manifest>
最佳答案
试试看
首先让您的BroadcastReceiver成为静态类或它自己的类,我不确定Android是否可以与非静态内部类一起使用。
其次,我不确定为什么您的接收者意图过滤器具有
filter.addDataScheme("http")
但是您缺少从Intent中启动服务的想法,如果不需要,请删除它。
关于android - 广播接收器不会收到 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48245258/