Android onBackPressed() 里调用 setResult(RESULT_OK) 无效


   从第一个Activity startActivityForResult 到第二个SecActivity ,在onBackPressed()里调用setResult(RESULT_OK),不能返回正确的值,如下:



 第一个Activity

public class MainActivity extends AppCompatActivity {

    public static final  int REQUEST_CODE = 1024 ;
    private TextView textView ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.tv1);
      /*  getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);*/

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,SecActivity.class);
                startActivityForResult(intent,REQUEST_CODE);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case REQUEST_CODE :
                if(resultCode == RESULT_OK)
                {
                    textView .setText("回调成功");
                }
                break;
        }
    }
}
secActivity

public class SecActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sec);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_OK);

    }

点击返回键,没有正确得到回调!这是为何?因为OnBackPressed() 会默认设置setResult(RESULT_CANCELED);

解决方案:

@Override
    public void onBackPressed() {

        setResult(RESULT_OK);
        super.onBackPressed();
    }




你可能感兴趣的:(android)