今天學校電力電子學作業超難
差點沒心力繼續學了zzz
昨天學向下一個Activity傳遞數據
今天學傳過去的數據接收之後再傳數據回來
一樣兩個Activity
public class ActRequestActivity extends AppCompatActivity implements View.OnClickListener {
private static final String mRequest = "開開心心";
private ActivityResultLauncher<Intent> register;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_act_request);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
TextView textView = findViewById(R.id.tv_request);
textView.setText("要發送的訊息:" + mRequest);
TextView tv_response = findViewById(R.id.tv_response);
findViewById(R.id.btn_request).setOnClickListener(this);
register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result != null){
Intent intent = result.getData();
if(intent != null && result.getResultCode() == Activity.RESULT_OK){
Bundle bundle = intent.getExtras();
String time = bundle.getString("response_time");
String msg = bundle.getString("response_msg");
String desc = String.format("現在時間:%s\n收到的訊息為%s",time,msg);
tv_response.setText(desc);
}
}
});
}
@Override
public void onClick(View view) {
Intent intent = new Intent(this, ActResponseActivity.class);
Bundle bundle = new Bundle();
bundle.putString("time", DateUtil.getNowTime());
bundle.putString("msg",mRequest);
intent.putExtras(bundle);
register.launch(intent);
}
}
public class ActResponseActivity extends AppCompatActivity implements View.OnClickListener {
private static final String mResponse = "328又在搞";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_act_response);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
TextView textView = findViewById(R.id.tv_request);
Bundle bundle = getIntent().getExtras();
String time = bundle.getString("time");
String msg = bundle.getString("msg");
String desc = String.format("現在時間:%s\n收到的訊息為%s",time,msg);
textView.setText(desc);
findViewById(R.id.btn_response).setOnClickListener(this);
TextView tv_response = findViewById(R.id.tv_response);
tv_response.setText("待返回的消息"+mResponse);
}
@Override
public void onClick(View view) {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("response_time", DateUtil.getNowTime());
bundle.putString("response_msg",mResponse);
intent.putExtras(bundle);
setResult(Activity.RESULT_OK,intent);
finish();
}
}
差不多先這樣 趕快去睡了
明天要去交作業呢 :(