如何访问在 BroadcastReceivers 的 MainActivity(layout) 中声明的 Switch 按钮

How to access Switch button that is declared in MainActivity(layout) in BroadcastReceivers

我有一个任务,当飞行模式为 ON/OFF 时,我必须更改开关按钮的状态。

我有一个主 activity,我在其中声明了 Switch Button,我想从 BroadcastReceiver Class

更改 Switch 的状态 on/off

接收方

public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    boolean isAirplaneModeOn = intent.getBooleanExtra("state", false);
    if(isAirplaneModeOn){
         What Should i do ?
    }
}
}

layout_main_activity

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hp.broadcastthroughmanifest.MainActivity">

<Switch
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="127dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintTop_creator="1" />
</android.support.constraint.ConstraintLayout>

尝试使用这样的事件总线 one 将事件 post 发送到 activity。从 activity 开始,当您收到事件时,您会更改开关的状态。 是这样的: - 你的广播 class:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean isAirplaneModeOn = intent.getBooleanExtra("state", false);
        if(isAirplaneModeOn){
            EventBus.getDefault().post(new SwitchEvent());
        }
    }
}

活动的class:

public class YourActivity{
    //declare your switch

    @Override
    public void onCreate() {
        setContentView(R.layout.layout_main_activity);
        //initialize your switch
    }

    @Override
     public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)  
    public void onMessageEvent(SwitchEvent event) {
        //update your switch element
    }
}

活动的class:

Public class SwitchEvent{
    public SwitchEvent(){
        //empty
    }
}