安卓專案compileSdk為32,在使用startActivityForResult()方法時發現Android studio提示此方法已經廢棄了。
目前的代替方案案例。
// 確保 app 的 build.gradle中已經引入了androidx.appcompat:appcompat
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.1' // 確定
}
從A跳到B,A頁面邏輯
package com.example.test1;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.test1.ui.login.LoginActivity; // B頁面例子
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static String TAG = "MainActivity";
private ActivityResultLauncher<Intent> register;
@SuppressLint("ResourceAsColor")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.my_button).setOnClickListener(this);
register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
Log.i(TAG, "onActivityResult: _____" + result);
if (result != null) {
Intent intent = result.getData();
if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
Bundle myBundle = intent.getExtras();
String my_name = myBundle.getString("my_name");
String my_sex = myBundle.getString("my_sex");
// 下一個Activity回退後 在此獲取返回的值
Log.i(TAG, "onCreate: 獲取返回傳值my_name__________" + my_name); // ___獲取返回傳值my_namezhangsan000
Log.i(TAG, "onCreate: 獲取返回傳值my_sex__________" + my_sex); // ___獲取返回傳值my_sex男
}
}
}
});
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.my_button) {
Intent intent = new Intent(this, LoginActivity.class);
// 用register.launch跳轉至B
register.launch(intent);
}
}
}
從A跳到B,B頁面回退邏輯
// B頁面的後退邏輯
public void myBack(View view) {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("my_name", "zhangsan000");
bundle.putString("my_sex", "男");
intent.putExtras(bundle);
// 攜帶意圖返回上一個頁面 RESULT_OK代表處理成功了
setResult(Activity.RESULT_OK, intent);
// 結束當前頁面
finish();
};