能否在代码中动态声明Manifest标签并添加android:enabled属性?
android:enabled Tag in Code? Great question! Let’s break this down clearly: You can’t directly create or modify the android:enabled tag in the Manifest file at runtime—but there’s a practical workaround that achieves the same goal.
Why Direct Manifest Edits Aren’t Possible
The Android Manifest is a static file that gets compiled into your app during the build process. Once the app is installed on a device, there’s no way to edit or add tags like android:enabled directly in this file. It’s locked in place after packaging.
The Workaround: Control Component State via PackageManager
Instead of editing the Manifest, you can dynamically toggle whether your receiver (or any component) is enabled using Android’s PackageManager API. This has the exact same effect as setting android:enabled="true" or false in the Manifest, but you can adjust it on-the-fly in code.
Here’s a code example tailored to your SMS receiver:
// Reference your SMS receiver component ComponentName smsReceiver = new ComponentName(context, YourSmsReceiver.class); PackageManager pm = context.getPackageManager(); // Enable the receiver (matches android:enabled="true") pm.setComponentEnabledSetting( smsReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP // Keep the app running after the change ); // Disable the receiver (matches android:enabled="false") pm.setComponentEnabledSetting( smsReceiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP );
Just replace YourSmsReceiver with the actual class name of your SMS receiver. This change takes effect immediately, and the system will respect this setting when delivering the SMS_RECEIVED intent.
内容的提问来源于stack exchange,提问作者SURYA N

