1. Activity 호출하기
다음과 같이, Intent 를 이용하여 다른 Actiivty 를 호출할 수 있다.
Intent intent = new Intent(this, SomeActivity.class);
startActivity(intent);
2. Activity 호출시 특정 Action 설정하기
2.1. Action 보내는 쪽
Intent intent = new Intent(this, SomeActivity.class);
intent.setAction(ACTION_NAME);
startActivity(intent);
2.2. Action 받는 쪽
Intent intent = getIntent();
if (intent.getAction().equals(ACTION_NAME)) {
...
}
3. Activity 호출시 데이타 보내기
3.1. 데이타 보내는 쪽
Intent intent = new Intent(this, SomeActivity.class);
intent.setAction(ACTION_NAME);
intent.putExtra(KEY, VALUE);
startActivity(intent);
3.2. 데이타 받는 쪽
Intent intent = getIntent();
int extra = intent.getIntExtra(KEY, DEFAULT_VALUE);
타입에 따라 getLongExtra(), getFloatExtra(), getLongExtra(), … 등등
4. 호출한 Activity 로 부터 리턴값 받기
A 라는 액티비티에서 B 라는 액티비티를 호출 후 B 액티비티에서 어떤 작업을 수행 후 결과값을 A 에게 보내줄때도 Intent 가 사용된다.
4.1. A 액티비티에서 에서 B 액티비티를 호출.
Intent intent = new Intent(MainActivity.this, TargetActivity.class);
startActivityForResult(intent, REQUEST_CODE);
4.2. B 액티비티에서 결과값 리턴.
Intent data = new Intent();
data.putExtra(KEY, VALUE);
setResult(RESULT_OK, data);
4.3. A 액티비티에서 결과값 받기.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
value = data.getCharSequenceExtra(KEY);
...
}
}
}
샘플 코드
다음의 GitHub 저장소에 올려 두었다.