Adapter发送LocalBroadcast给Activity,Activity没有收到

问题描述

使用继承了RecyclerView.Adapter的一个Adapter,在这个Adapter的ViewHolder中有一个TextView,希望点击这个TextView来传递数据并启动一个Activity来展示,我谷歌了一些方法发现可以使用LocalBroadcast来实现但是没有成功。我想知道如何才能在Activity中收到广播或者有什么更好的传递数据的方法?

问题出现的环境背景及自己尝试过哪些方法

调试过程中我发现TextView被点击了,但是Activity的onCreate没有调用,自然就没有收到广播,于是我在发送广播前调用来startActivity(),onCreate()调用了但是广播依然没有收到。我在已经进行过创建的MainActivity中运行来相同的代码,MainActivity可以收到广播,所以我认为广播没有收到是与SearchActivity没有被创建有关

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)
Manifext.xml如下

<activity
            android:name=".MainActivity"
            android:theme="@style/Theme.AppCompat.DayNight.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.SearchActivity"
            android:theme="@style/Theme.AppCompat.DayNight.NoActionBar" />

BaseActivity的代码

public class BaseActivity extends AppCompatActivity {
    // MainApplication.getContext(), getContext()返回值是getApplicationContext()
    protected Context mContext = MainApplication.getContext();
    
}

Adapter的onBindView代码

@Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        HomeCategoryModel homeCategoryModel = mHomeCategoryModelList.get(position);
        // debug
        Log.i(LOG_TAG, "debug onBindViewHolder position:" + position + ", homeCategoryModel.category.name:" + homeCategoryModel.getCategory().getName());

        holder.categoryName.setText(homeCategoryModel.getCategory().getName());
        holder.seeAll.setOnClickListener(v -> {
            //TODO: 点击发送跳转请求跳转搜索页面,数据为查询类别
            int categoryId = homeCategoryModel.getCategory().getId();
            Intent intent = new Intent(LOG_TAG);
            intent.putExtra("categoryId", categoryId);
            mContext.startActivity(new Intent(mContext, SearchActivity.class));
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
            // debug
            Log.i(LOG_TAG, "debug holder.seeAll.setOnClickListener categoryId:" + categoryId);
        });
        // CategorySuggestAdapter
        List<Music> musicList = new ArrayList<>(homeCategoryModel.getMusicList());
        CategorySuggestAdapter categorySuggestAdapter = new CategorySuggestAdapter(mContext, musicList);
        holder.categorySuggest.setAdapter(categorySuggestAdapter);
        // 关闭潜逃滑动
        holder.categorySuggest.setNestedScrollingEnabled(false);
        // 定长
        holder.categorySuggest.setHasFixedSize(true);
        // 水平
        holder.categorySuggest.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
    }

Activity的代码

public class SearchActivity extends BaseActivity {
    // log tag
    private static final String LOG_TAG = SearchActivity.class.getSimpleName();

    // UI
    @BindView(R.id.imageview_search_return)
    ImageView mReturnImageView;
    @BindView(R.id.searchview_search_music)
    SearchView mSearchView;
    @BindView(R.id.recyclerview_search_result)
    RecyclerView mRecyclerView;

    /**
     * {@link com.hwxy.fafm.adapter.CategoryAdapter}的广播接收器接收请求数据
     */
    private BroadcastReceiver mCategoryAdapterMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            int categoryId = intent.getIntExtra("categoryId", -1);
            // debug
            Log.i(LOG_TAG, "debug mCategoryAdapterMessageReceiver get categoryId: " + categoryId);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acticiaty_search);
        ButterKnife.bind(this);

        // 注册CategoryAdapter广播接收器
        LocalBroadcastManager.getInstance(mContext)
                .registerReceiver(mCategoryAdapterMessageReceiver,
                        new IntentFilter(CategoryAdapter.class.getSimpleName()));
        // debug
        Log.i(LOG_TAG, "debug onCreate registerReceiver");
    }

    @Override
    protected void onDestroy() {
        // 取消注册
        LocalBroadcastManager.getInstance(mContext)
                .unregisterReceiver(mCategoryAdapterMessageReceiver);
        super.onDestroy();
    }
}

mContext均是getApplicationContext()

你期待的结果是什么?实际看到的错误信息又是什么?

我希望可以将数据传到Activity, 实际的log,广播接受器没有生效。

2019-04-18 19:00:40.545 21253-21253/com.hw.f I/CategoryAdapter: debug holder.seeAll.setOnClickListener categoryId:2
2019-04-18 19:00:40.586 21253-21253/com.hw.f I/SearchActivity: debug onCreate registerReceiver
阅读 3k
1 个回答

估计问题是在IntentFilterCategoryAdapter.class.getSimpleName()

换这个看收到吗

Adapter

Intent intent = new Intent("custom-event-name");  //非常重要!!! 
intent.putExtra("categoryId", categoryId);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Activity

 @Override
 public void onCreate(Bundle savedInstanceState) {
    
    LocalBroadcastManager.getInstance(this).registerReceiver(
        mMessageReceiver,
        new IntentFilter ("custom-event-name")  //非常重要!!! 
    );
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
       // Get extra data included in the Intent
        int categoryId = intent.getIntExtra("categoryId", -1);
        // debug
        Log.i(LOG_TAG, "debug mCategoryAdapterMessageReceiver get categoryId: " + categoryId);
    }
};

@Override
protected void onDestroy() {
    // Unregister since the activity is about to be closed.
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
    super.onDestroy();
}

修改

我想知道如何才能在Activity中收到广播或者有什么更好的传递数据的方法?

还有另一个写法,就是在SearchActivity那里直接用getIntExtra()的方式

Adapter

Intent intent = new Intent();   
intent.putExtra("categoryId", categoryId);
startActivity(intent);

SearchActivity

setContentView(R.layout.acticiaty_search);
int categoryId = intent.getIntExtra("categoryId", -1);
   


撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏