gpt4 book ai didi

android - BroadcastReceiver:以编程方式设置 android:process

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:38 25 4
gpt4 key购买 nike

我希望我的应用检测外部存储的状态是否发生变化。首先在我的 AndroidManifest 中定义了一个 BroadcastReceiver。在这里,我可以像这样设置 android:processandroid:exported 属性:

    <receiver android:name=".StorageStateReceiver" android:process=":storage_state" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.MEDIA_UNMOUNTED" />
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_EJECT" />
<action android:name="android.intent.action.MEDIA_BAD_REMOVAL" />
<data android:scheme="file" />
</intent-filter>
</receiver>

然后我意识到我只在一个 Activity 中使用这个接收器,所以不需要在应用程序启动时实例化它,而是我可以在代码中以编程方式定义它。这是我想出的:

BroadcastReceiver StorageStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Do what needs to be done
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_EJECT);
filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
filter.addDataScheme("file");
getApplicationContext().registerReceiver(StorageStateReceiver, filter);

我将此代码放在 Activity 的 onCreate() 方法中。

但是我找不到从代码中设置process 的方法。我已阅读有关 BroadcastReceiver 和 Context 类的文档。 BroadcastReceiver 似乎没有托管任何让您定义进程名称的方法。另一方面,registerReceiver() 可以接受两个额外的参数:String broadcastPermissionHandler scheduler。 Handler 听起来很有前途,但我找不到可以接受字符串形式的进程名称的 Handler 构造函数。我觉得我的想法用完了。有没有办法以编程方式设置进程名称?

最佳答案

Then I realized that I only use this receiver in one single Activity, so there's no need to have it instantiated when the app starts, instead I can define it programmatically in code.

list 注册的 BroadcastReceiver 不会“在应用程序启动时实例化”。它仅在发送匹配的广播时实例化。

But I can't find a way to set process from code.

那是因为这是不可能的。此外,您不需要它,它会浪费 RAM、CPU 和电池,从而损害用户的利益。您也不应该在 list 条目中拥有 android:process 属性,除非您完全且准确地知道为什么您需要另一个进程。绝大多数 Android 应用都没有。

关于android - BroadcastReceiver:以编程方式设置 android:process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16126030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com