我有一个FragmentActivity正在为结果启动另一个活动。当被调用的活动完成时,不会调用onActivityResult。我使用AppCompatActivity活动(从FragmentActivity扩展)是否有所不同?文档说结果将返回到调用片段,在这种情况下,它不是片段,它是一个活动。这是代码,非常简单:
MainActivity:
public class SMSEmailActivityNew extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setup activity....
Intent i = new Intent(this, EulaActivity.class);
i.putExtra(Globals.keyFileName,Globals.FILE_EULA );
startActivityForResult(i,RESULT_OK);
}
//this method is never called
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//dowork .....
}
}
被叫活动:
EulaActivity extends AppCompatActivity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set up activity ....
}
public void onClick(View v) {
Intent result = new Intent();
if (bPermissionGranted) {
setResult(Activity.RESULT_OK, result);
// Determine if EULA was accepted this time
getSharedPreferences().edit().putBoolean(Globals.KEY_EULA_ACCEPTED, true).apply();
} else {
setResult(Activity.RESULT_CANCELED, result);
}
finish();
}
}
答案 0 :(得分:4)
根据documentation,您需要将requestId
大于或等于0. {在您的情况下RESULT_OK
为-1
。此外,RESULT_OK
的行为与结果代码类似,与请求代码不同,startActivityForResult
需要请求代码。
像这样startActivityForResult(intent, 0);
使用EulaActivity
完成finishActivity(yourPreviousRequestCode);
,在这种情况下0
。
答案 1 :(得分:0)
尝试此解决方案: -
MainActivity.java
//Define variable
public static int REQUEST_CODE = 233;
public class SMSEmailActivityNew extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setup activity....
Intent i = new Intent(this, EulaActivity.class);
i.putExtra(Globals.keyFileName,Globals.FILE_EULA );
startActivityForResult(i, REQUEST_CODE); //Change here
}
//this method is never called
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if(data != null && data.hasExtra("MESSAGE")) {
String resStr = data.getStringExtra("MESSAGE");
Toast.makeText(MainActivity.this, resStr, Toast.LENGTH_SHORT).show();
}
}else if(resultCode == RESULT_CANCELED)
Toast.makeText(MainActivity.this, "Canceled", Toast.LENGTH_SHORT).show();
}
}
}
EulaActivity.java
EulaActivity extends AppCompatActivity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set up activity ....
}
public void onClick(View v) {
Intent result = new Intent();
result.putExtra("MESSAGE","Eula Accepted Set");
if (bPermissionGranted) {
setResult(Activity.RESULT_OK, result);
// Determine if EULA was accepted this time
getSharedPreferences().edit().putBoolean(Globals.KEY_EULA_ACCEPTED, true).apply();
} else {
setResult(Activity.RESULT_CANCELED, result);
}
finish();
}
}