Android – Starting an Activity PART 2

You can read PART 1 here. You can launch activities on demand with startActivity() and startActivityForResult()

startActivity()

Launches a new activity and it does not return any information when the activity exits. It has one argument, an intent to start.

start activiy get result and check if activity exists, <span>Android – Starting an Activity PART 2</span>, KandZ

You can read more here.

startActivityForResult()

Launches an activity and you will get a result when the activity finished. It can take up to 3 arguments, the intent to start, the request code (int) that identifies the request to the 2nd activity and options as a bundle.

start activiy get result and check if activity exists, <span>Android – Starting an Activity PART 2</span>, KandZ

At the 1st activity, you need to override the onActivityResult() to get the result from the 2nd activity. Check if the request was successful and if it is the same request code.

start activiy get result and check if activity exists, <span>Android – Starting an Activity PART 2</span>, KandZ

The 2nd activity will return the result with the help of an intent. You must use setResult() to set the returning result. And of course use finish() to close the activity

start activiy get result and check if activity exists, <span>Android – Starting an Activity PART 2</span>, KandZ

The first two lines get the name entered from the user. The third line creates an intent, and then the intent will take extra data(the name) on line four. Next uses the setResult(), the first arguments says that the request is successful and the second is the intent we send back to the first activity. The last line closes/terminates the second activity. Then onActivityResult is called in the first activity, which checks if request code is the same, and the request was successful. You can see the first line from logcat below, it is the name returned from the second activity.

start activiy get result and check if activity exists, <span>Android – Starting an Activity PART 2</span>, KandZ

Check if activity exists

Use resolveActivity() method on the intent to check if the activity exists.

start activiy get result and check if activity exists, <span>Android – Starting an Activity PART 2</span>, KandZ
91900cookie-checkAndroid – Starting an Activity PART 2Android – Starting an Activity PART 2

Related posts