Activityで別のActivityのUI更新を制御するブロードキャスト

1913 ワード

MainActivityでは、ブロードキャストにより、ボタン2をクリックしてボタン1の名前を変更する.
public class MainActivity extends AppCompatActivity {
    private Button  button1;
    private Button button2;
// action
    public static final String action = "jason.broadcast.action";
    private ButtonReceiver receiver;
    private String textLine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button2 =(Button)findViewById(R.id.button_2);
        button1 =(Button)findViewById(R.id.button_1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(MainActivity.this,Main2Activity.class);
                startActivity(intent1);
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 
                Intent intent = new Intent(action);
                intent.putExtra("textLine", "text");
                sendBroadcast(intent);
            }
        });
            // 
        receiver = new ButtonReceiver();
        IntentFilter intentFilter = new IntentFilter("jason.broadcast.action");
        registerReceiver(receiver, intentFilter);
    }
    // 
    public class ButtonReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
                // 
            String textLine = intent.getExtras().getString("textLine");
            button1.setText(textLine);
            Toast.makeText(context,textLine,Toast.LENGTH_SHORT).show();
        }

    }

  

    // 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}