본문 바로가기

안드로이드

안드로이드 : 액티비티와 인텐트

액티비티를 생성하고 다른 Application에서 호출하도록 하려면

AndroidManifest.xml 파일에서 Activity 에 Intent Filter를 추가

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="com.example.ACTION_VIEW"/>
                <category android:name="android.intent.category.DEFAUL"/>
                
            </intent-filter>

다른 Application에서 Intent 를 defalut constructor로 생성하고

setAction 메소드에 com.example.ACTION_VIEW 을 지정하고 startActivity 를 호출하면 다른 애플리케이션의 Activity 를 호출할 수 있습니다.

 

Activity 사이의 데이터 교환

1. Main에서 하위 Activity 에게 데이터를 넘겨주는 방법

Intent를 생성하고 putExtra라는 메소드를 이용해서 문자열로 이름을 정하고 값을 설정해주면 됩니다.

 

2. 하위 Activity 에서는 intent 속성을 호출해서 get 자료형 Extra(이름) 을 호출하면 됩니다.

앞에서 넘겨주지 않은 이름을 사용하면 null 이 리턴 됩니다.

넘겨줄 수 있는 데이터는 기본 자료형과 Serializable 또는 Parceable 인터페이스를 implements 한 데이터가 가능합니다.

 

2. 하위 Activity 에서 상위 Activity 에게 데이터를 전달하고자 하는 경우

=> 상위 Activity 에서 하위 Activity 를 호출할 때 startActivityForResult(intent:Intent, requestCode:Int) 로 호출

requestCode는 구분하기 위한 정수 값

 

=> 하위 Activity 에서는 Intent() 로 Intent를 생성해서 putExtra 메소드를 이용해서 데이터를 설정하고 setResult(구분하기 위한 정수 값, intent:Intent)

 

상위 Activity 에서는 onActivityResult(requstCode:Int, resultCode:Int, intent:Intent?) 를 재정의 해서 내가 호출할 때 대입한 코드와 requestCode를 비교하여 하위 Activity 에서 설정한 구분하기 위한 정수 값과 resultCode 를 비교한 후 intent를 이용해서 데이터를 읽어내야 합니다.

 

 

MainActivity.kt

package kr.co.tjoeun.myapp1102

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        gosubutton.setOnClickListener {

            // 새로운 Intent 를 생성
            val intent : Intent = Intent(this, SubActivity::class.java)
            // 화면 출력
            // startActivity(intent)

            // 넘겨줄 데이터 설정
            intent.putExtra("data", "상위에서 넘겨주는 데이터")
            // 하위에서 넘겨받고자 하는 경우 호출
            // 정수는 하위 Activity 를 구분하기 위한 숫자
            startActivityForResult(intent, 100)
        }

        camera.setOnClickListener {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            startActivityForResult(intent, 50)


        }
    }

    // startActivityForResult 로 하위 Activity 를 호출 한 경우
    // 하위 Activity 가 소멸 되면 호출 되는 메소드
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 넘어온 데이터를 출력
        if(requestCode == 10 && requestCode == 200) {
            maintext.text = data!!.getStringExtra("msg")
        }else if(requestCode == 50 && resultCode == Activity.RESULT_OK) {
            //  이미지 데이터 가져오기
            val bitmap = data?.extras!!["data"] as Bitmap?
            // 이미지 뷰에 출력
            imageview.setImageBitmap(bitmap)
        }
    }
}

 

 

SubActivity.kt

package kr.co.tjoeun.myapp1102

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_sub.*
class SubActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sub)


        // 상위 Activity 에서 넘겨준 데이터를 가져오기

        val intent = intent
        // 없는 이름을 사용하면 null
        val data : String? = intent.getStringExtra("data")
        // 가져온 데이터 출력
        subtext.text = data

        finish.setOnClickListener {
            /*
            val intent:Intent = Intent(this, MainActivity::class.java)
            startActivity(intent)

             */

            // 상위 Activity 에게 데이터 보내기
            val intent = Intent()
            intent.putExtra("msg", "하위에서 넘겨주는 데이터")
            // 하위 Activity 에서 여러 데이터를 보낼 때 구분하기 위한 번호
            setResult(200, intent)
            // 현재 Activity 를 제거
            finish()
        }
    }
}

 

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/maintext"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="하위 액티비티로 이동"
        android:id="@+id/gosubutton"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="카메라 앱 실행"
        android:id="@+id/camera"/>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/imageview"/>

</LinearLayout>

 

 

activity_sub.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SubActivity"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="하위 액티비티"
        android:id="@+id/subtext"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="현재 액티비티 제거"
        android:id="@+id/finish"/>

</LinearLayout>

 

Resource 에 같이 사용 되는 자원을 삽입

=> 이름을 일련번호 형태로 사용

이미지는 정수로 관리 되기 때문!

 

 

'안드로이드' 카테고리의 다른 글

안드로이드 : 웹 서버 연결  (0) 2020.11.04
안드로이드 : Thread 와 Handler / 서버 통신  (0) 2020.11.03
안드로이드  (0) 2020.10.29
안드로이드 : 목록 대화 상자  (0) 2020.10.28
안드로이드 : 대화 상자  (0) 2020.10.28