安卓我的项目 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();};