本文介绍了如何从BroadcastReceiver更新RecyclerView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AndroidManifest.xml 中,我有一个 BroadcastReceiver :

<receiver android:name=".SmsMonitor">
    <intent-filter android:priority="-100">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

在我的 MainActivity 中,我有 RecyclerView 以及接收到的SMS列表.

In my MainActivity, I have RecyclerView with a list of received SMS.

我的问题是-如何在我的 BroadcastReceiver "SmsMonitor"中更新 RecyclerView ,以防在运行应用程序时收到新的SMS?

My question is - How I can update the RecyclerView from my BroadcastReceiver "SmsMonitor" in case new SMS received when the application is running?

UPD:我的意思是我需要在两个接收器中同时解决这两种状态-运行应用程序以及未运行应用程序时的状态.因为我必须在电话工作期间一直接收短信.如果应用程序正在运行,我想更新 RecyclerView .

UPD: I mean I need solution for both states - for running application AND for state when application is not running, in one receiver. Because I have to take SMS all time while phone is working. And in case the application is running I want to update RecyclerView.

推荐答案

我尝试通过 Service 完成此操作,但未成功.但是我找到了简单的解决方案:

I tried to do it through the Service, but I did not succeed.But I found simple solution:

我仍然有 BroadcastReceiver SmsMonitor ,已在 AndroidManifest.xml

在我创建 RecyclerAdapter 实例的那一刻:

And in the point where I create instance of my RecyclerAdapter:

mainAdapter = new MainAdapter(this);

此后,我注册了另一个 BroadcastReceviver :

After this I register another BroadcastReceviver:

BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        setInitialData();
        mainAdapter.notifyDataSetChanged();
    }
};
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
this.registerReceiver(br, filter);

然后在 setInitialData()中,重新创建 RecyclerView 的所有数据列表.

And in setInitialData() I recreate all list of data for RecyclerView.

现在我有两个独立工作的 BroadcastReceiver .首先使用 AndroidManifest.xml 中的 BroadcastReceiver ,然后使用在MainActivity中注册的 BroadcastReceiver .

And now I have two independently working BroadcastReceiver. The first working the BroadcastReceiver from the AndroidManifest.xml, and then working the BroadcastReceiver registered in MainActivity.

这篇关于如何从BroadcastReceiver更新RecyclerView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 04:11