Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

android - onActivityResult doesn't work?

I am facing with a problem related startActivityForResult()

To start SecondActivity from FirstActivity :

Intent intent = new Intent();
intent.setClass(FirstActivity.this, SecondActivity.class);
intent.putExtra("key1", "12345");
startActivityForResult(intent, 0);

And handles result :

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //TODO handle here. 
}

To send the message to FirstActivity from SecondActivity :

in SecondActivity :

setResult(0);

I can't handle the result on onActivityResult in FirstActivity. It never works for my application.

My OS is : 1.5

What is wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

startActivityForResult is meant to be used for situations where you want to select a piece of data, or perform some sort of action that your Activity or application cannot do.

For example, you want to pick a contact, so you launch the contacts application, the user chooses the person they want, and you get sent the result. Or you want to take a photo, so you launch the camera application and ask it to send you the photo once it's done. This action is completely separate from your first activity that calls startActivityForResult.

The Activity you're launching will not send you the result until that Activity has completed, i.e. finish() has been called.

So in your case, you need to call this in SecondActivity:

setResult(...);
finish();

before FirstActivity will receive the result in its onActivityResult method. Of course, this means that SecondActivity is now gone and FirstActivity is top of the stack again.


It's not possible to send the result to FirstActivity then close it while keeping SecondActivity still active. In this case you should just handle whatever this 'result' is in SecondActivity, or send it off to a Service you define to do whatever processing it is you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...