android - Sending a broadcast to MainActivity and then showing a TextView

南笙酒味 提交于 2019-11-29 12:57:50

Step 0 : Define an action :

public static final String ACTION_SHOW_TEXT= "showText";

Step 1 : Create your Broadcast receiver in your MainActivity :

BroadcastReceiver  mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (myText != null) {
                myText.setVisibility(View.VISIBLE);
            }
        }
    };

Step 2 : Add the register and unregister events in your MainActivity :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    LocalBroadcastManager.getInstance(this)
            .registerReceiver(mReceiver, new IntentFilter(ACTION_SHOW_TEXT));
}

@Override
protected void onDestroy() {
    super.onDestroy();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
}

Step 3 : Whenever you want to display your TextView, call from anywhere :

Intent i = new Intent(MainActivity.ACTION_SHOW_TEXT);
                        i.putExtra("success", true);
                        LocalBroadcastManager.getInstance(this)
                                .sendBroadcast(i);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!