Android BroadcastReceiver注册问题:无有效新版教程,动态注册可行
问题:静态注册BroadcastReceiver失效,动态注册正常的原因分析
找不到2017年之后关于BroadcastReceiver静态注册的有效教程,按2017年及更早的教程操作无法生效,但通过Java代码动态注册BroadcastReceiver却能正常运行,请问操作哪里有误?
在MainActivity::onCreate中添加以下代码后,无论AndroidManifest.xml中是否包含<receiver>条目,广播都能正常被接收:
registerReceiver( new DemoReceiver(), new IntentFilter("com.example.receiverdemo.CUSTOM_INTENT") );
基础示例代码
MainActivity.java
package com.example.receiverdemo; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.TestButton) .setOnClickListener(view -> sendBroadcast(new Intent("com.example.receiverdemo.CUSTOM_INTENT")) ); } }
DemoReceiver.java
package com.example.receiverdemo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class DemoReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("FOO", "com.example.receiverdemo.DemoReceiver::onReceive called."); Toast.makeText(context, "Intent Received!", Toast.LENGTH_SHORT).show(); } }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example.receiverdemo"> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.ReceiverDemo" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="com.example.receiverdemo.DemoReceiver" android:exported="true"> <intent-filter> <action android:name="com.example.receiverdemo.CUSTOM_INTENT"/> </intent-filter> </receiver> </application> </manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/TestButton" android:layout_width="wrap_content" android:layout_height="48dp" android:layout_gravity="center" android:text="TEST BROADCAST RECEIVER" /> </FrameLayout>
内容的提问来源于stack exchange,提问作者laj0
相关产品推荐
相关产品推荐

