더보기

-MainActivity.java-

package com.example.my15_touchevent;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    View view1,view2;
    ScrollView scrollView;
    GestureDetector detector;
    EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);
        view1 = findViewById(R.id.view1);
        view2 = findViewById(R.id.view2);
        scrollView = findViewById(R.id.scrollView);


        view1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction(); //현재 이벤트 상태를 가져옴
                float  curX = event.getX();
                float curY = event.getY();

                if(action == event.ACTION_DOWN){
                    printString("손가락 눌림 : "+curX+", "+curY);
                }else if(action == event.ACTION_MOVE){
                    printString("손가락 움직임 : "+curX+", "+curY);
                }else if (action == event.ACTION_UP){
                    printString("손가락 뗌 : "+curX+", "+curY);
                }


                return true;
            }
        });

        view2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);

                return true;
            }
        });

        detector=new GestureDetector(this, new GestureDetector.OnGestureListener() {
            //화면이 눌렸을 때
            @Override
            public boolean onDown(MotionEvent e) {
                String distannceX;
                printString("onDown() 호출됨=>");
                return true;
            }

            // 화면이 눌렸다 떼어지는 경우
            @Override
            public void onShowPress(MotionEvent e) {
                printString("onShowPress() 호출됨");
            }

            //화면이 한손가락으로 눌렸다 떼어지는 경우
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                printString("onsingleTapUp() 호출됨");
                return true;
            }

            //화면이 눌린채 일정한 속도와 방향으로 움직였다 떼는 경우
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                printString("onScroll() 호출됨"+distanceX+", "+distanceY);
                return true;
            }

            //화면을 손가락으로 오랫동안 눌렀을 경우
            @Override
            public void onLongPress(MotionEvent e) {
                printString("onLongPress() 호출됨");
            }

            //화면이 눌린채 가속도를 붙여 손가락을 움직였다 떼는 경우
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                printString("onFling() 호출됨 =>"+velocityX+", "+velocityY);
                return true;
            }
        });

    }



    private void printString(String s) {
        textView.append(s +"\n");

        scrollView.fullScroll(View.FOCUS_DOWN); //포커스가 젤 아래로 이동됨
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if(keyCode == KeyEvent.KEYCODE_BACK ){
            printString("시스템에서 [Back]버튼이 눌림");
            return true;
        }else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
            printString("시스템에서 [VOLUME_UP]버튼이 눌림");
            return true;
        }else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            printString("시스템에서 [volume_down]버튼이 눌림");
            return true;
        }else if(keyCode == KeyEvent.KEYCODE_ENTER) {
            printString("시스템에서 [Enter]버튼이 눌림");
            return true;
        }

       /* else if(keyCode == KeyEvent.KEYCODE_V){
            if(event.isAltPressed()){
                printString("시스템에서 [ALT_V]버튼이 눌림");
                return true;
            }

        }*/



        return false;
    }
}

'For developer > Android' 카테고리의 다른 글

(Android)my17_orientation,my18_orientation2(정리x)  (0) 2020.05.27
(Android)my16_progress  (0) 2020.05.27
(Android)my14_smsservice  (0) 2020.05.27
(Android)my13_service  (0) 2020.05.21
(Android)my11_dialog_대화상자  (0) 2020.05.21

백그라운드에서 대기하여 문자롤 수신 하였을 때 엑티비티 실행

 

 

1.BroadCastReceiver.java 생성

 

File -> New -> other -> broadcast receiver

 

더보기

-MainActivity.java-

package com.example.my14_smsservice;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkDangerousPermissions();
    }

    private void checkDangerousPermissions() {
        String[] permissions = {
                Manifest.permission.RECEIVE_SMS

        };

        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        for (int i = 0; i < permissions.length; i++) {
            permissionCheck = ContextCompat.checkSelfPermission(this, permissions[i]);
            if (permissionCheck == PackageManager.PERMISSION_DENIED) {
                break;
            }
        }

        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "권한 있음", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "권한 없음", Toast.LENGTH_LONG).show();

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
                Toast.makeText(this, "권한 설명 필요함.", Toast.LENGTH_LONG).show();
            } else {
                ActivityCompat.requestPermissions(this, permissions, 1);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, permissions[i] + " 권한이 승인됨.", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, permissions[i] + " 권한이 승인되지 않음.", Toast.LENGTH_LONG).show();
                }
            }
        }
    }





}

-snsDisplay.java-

package com.example.my14_smsservice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SmsDisplayActivity extends AppCompatActivity {

    Button btnTitle,btnClose;
    TextView tvMsg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms_display);

        tvMsg = findViewById(R.id.tvMsg);
        btnTitle = findViewById(R.id.btnTitle);
        btnClose = findViewById(R.id.btnClose);

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Intent display = getIntent();
        processIntent(display);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        processIntent(intent);
    }

    private void processIntent(Intent display) {
        String sender = display.getStringExtra("sender");
        String receivedDate = display.getStringExtra("receivedDate");
        String contents = display.getStringExtra("contents");

        if(sender!=null){
            btnTitle.setText(sender +" 에서 문자 수신");
            tvMsg.setText("["+receivedDate+"]\n"+contents);
        }
    }
}

-MyReveiver.java-

package com.example.my14_smsservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "MyReceiver";
    public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: 호출됨");

        Bundle bundle = intent.getExtras();
        SmsMessage[] messages = parseSmsMessage(bundle);

        if(messages != null && messages.length>0){
            Log.d(TAG, "SMS를 수신하였습니다");

            String sender = messages[0].getOriginatingAddress();    //보낸사람
            Log.d(TAG, "sender : "+sender);

            Date receivedDate = new Date(messages[0].getTimestampMillis()); //받은 날짜
            Log.d(TAG, "receivedDate : "+receivedDate);

            String contents = messages[0].getMessageBody(); //내용
            Log.d(TAG, "contents : "+contents);

            Intent display = new Intent(context,SmsDisplayActivity.class);

            display.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);
            /*
            * NWE TASK : 새창 띄움
            * CLEAR TOP :
            * SINGLE TOP : 똑같은 창을 띄우지 말고 기존 창을 써라
            * */

            display.putExtra("sender",sender);
            display.putExtra("receivedDate",dateFormat.format(receivedDate));
            display.putExtra("contents",contents);
            context.startActivity(display);
        }
    }

    private SmsMessage[] parseSmsMessage(Bundle bundle) {
        Object[] objs = (Object[]) bundle.get("pdus");  //pdu:메세지 1,2,etc.. 가르킴 최신메세지는 0번임.
        SmsMessage[] messages = new SmsMessage[objs.length];

        for(int i=0;i<objs.length;i++){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                String format = bundle.getString("format");
                messages[i] = SmsMessage.createFromPdu((byte[]) objs[i],format);
            }else{
                messages[i] = SmsMessage.createFromPdu((byte[]) objs[i]);
            }
        }

        return messages;
    }
}

'For developer > Android' 카테고리의 다른 글

(Android)my16_progress  (0) 2020.05.27
(Android)my15_touchevent  (0) 2020.05.27
(Android)my13_service  (0) 2020.05.21
(Android)my11_dialog_대화상자  (0) 2020.05.21
(Android)my10_intentresult  (0) 2020.05.21

서비스란 안드로이드의 대표 컴포넌트 중 하나로 백그라운드에서 필요한 작업시 사용할 수 있는 컴포넌트를 이야기 함.

 

 

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText.getText().toString();
                Log.d(TAG, "onClick: "+name);

                Intent intent = new Intent(getApplicationContext(),MyService.class);
                intent.putExtra("command","show");
                intent.putExtra("name",name);
                startService(intent);
            }
        });

 서비스를 실행 할 때는 startService 메소드를 사용한다.

 

 

-Service.java-

public class MyService extends Service {
    private static final String TAG = "MainMyService";

    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: 호출됨");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {  //flags: 잘 실행되고 있는지 코드값 리턴
        Log.d(TAG, "onStartCommand: 호출됨 "+flags+", "+startId);

        if(intent ==null){
            return Service.START_STICKY;    //다시 리스타트
        }else{
            processCommand(intent);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void processCommand(Intent intent) {
        String command = intent.getStringExtra("command");
        String name = intent.getStringExtra("name");

        Log.d(TAG, "processCommand: "+command+", "+name);

        for(int i=0;i<5;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "Waiting :"+ i+" second...");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: 호출됨");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

 서비스 엑티비티가 호출되면 onCreate() ->onstartCommand() 순으로 실행이 된다

메인에서 넘어온 INTENT가 널 값이 아니면 processCommand() 메소드가 실행이 되고 백그라운드 상태에서 동작이 되도록 한다. 

 

-Main.java-

 button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),MyService.class);
                stopService(intent);
            }
        });

메인 엑티비티에서  서비스 종료를 시키려면 stopService메소드를 사용하여 종료를 시킨다.

 

종료 버튼을 누르면

 

-Service.java-

@Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: 호출됨");
    }

서비스가 종료되어 onDestory()가 호출되어 종료되어진다.

더보기

-Main.java-

package com.example.my13_service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    EditText editText;
    Button button1,button2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText=findViewById(R.id.editText);
        button1=findViewById(R.id.button1);
        button2=findViewById(R.id.button2);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText.getText().toString();
                Log.d(TAG, "onClick: "+name);

                Intent intent = new Intent(getApplicationContext(),MyService.class);
                intent.putExtra("command","show");
                intent.putExtra("name",name);
                startService(intent);
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),MyService.class);
                stopService(intent);
            }
        });
    }
}

 

-service.java-

package com.example.my13_service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    private static final String TAG = "MainMyService";

    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: 호출됨");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {  //flags: 잘 실행되고 있는지 코드값 리턴
        Log.d(TAG, "onStartCommand: 호출됨 "+flags+", "+startId);

        if(intent ==null){
            return Service.START_STICKY;    //다시 리스타트
        }else{
            processCommand(intent);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void processCommand(Intent intent) {
        String command = intent.getStringExtra("command");
        String name = intent.getStringExtra("name");

        Log.d(TAG, "processCommand: "+command+", "+name);

        for(int i=0;i<5;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "Waiting :"+ i+" second...");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: 호출됨");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

'For developer > Android' 카테고리의 다른 글

(Android)my15_touchevent  (0) 2020.05.27
(Android)my14_smsservice  (0) 2020.05.27
(Android)my11_dialog_대화상자  (0) 2020.05.21
(Android)my10_intentresult  (0) 2020.05.21
(my09_layoutinflate)인플레이트  (0) 2020.05.21

 

 

 private void showMessage() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("안내");
        builder.setMessage("종료하시겠습니까?");
        builder.setIcon(android.R.drawable.ic_dialog_alert);

        builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String message = "예 버튼이 눌렸습니다. : "+which;
                tvAlarm.setText(message);
            }
        });

        builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String message = "아니오 버튼이 눌렸습니다. : "+which;
                tvAlarm.setText(message);
            }
        });

        builder.setNeutralButton("취소", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String message = "취소 버튼이 눌렸습니다. : "+which;
                tvAlarm.setText(message);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

 

-전체코드-

더보기

 

 -Main.xml-

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >


    <TextView
        android:id="@+id/tvAlarm"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="69dp"
        android:gravity="center"
        android:text="버튼을 누르면 대화상자가 뜹니다"
        android:textSize="24dp" />

    <Button
        android:id="@+id/btnOpen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvAlarm"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginStart="160dp"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="92dp"
        android:layout_marginEnd="163dp"
        android:layout_marginRight="163dp"
        android:text="대화상자 열림" />
</RelativeLayout>

 

 

-Main.java-

package com.example.my11_dialog;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.provider.AlarmClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button btnOpen;
    TextView tvAlarm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvAlarm = findViewById(R.id.tvAlarm);
        btnOpen = findViewById(R.id.btnOpen);
        btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessage();
            }


        });
    }
    private void showMessage() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("안내");
        builder.setMessage("종료하시겠습니까?");
        builder.setIcon(android.R.drawable.ic_dialog_alert);

        builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String message = "예 버튼이 눌렸습니다. : "+which;
                tvAlarm.setText(message);
            }
        });

        builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String message = "아니오 버튼이 눌렸습니다. : "+which;
                tvAlarm.setText(message);
            }
        });

        builder.setNeutralButton("취소", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String message = "취소 버튼이 눌렸습니다. : "+which;
                tvAlarm.setText(message);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();










































    }
}


'For developer > Android' 카테고리의 다른 글

(Android)my14_smsservice  (0) 2020.05.27
(Android)my13_service  (0) 2020.05.21
(Android)my10_intentresult  (0) 2020.05.21
(my09_layoutinflate)인플레이트  (0) 2020.05.21
(Andorid)intentresult  (0) 2020.05.18

Intent에 결과를 저장하여 sub화면으로 넘기는 법

btnMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PersonDto person1 = new PersonDto("css",3333);

                Intent intent = new Intent(MainActivity.this,Sub1Activity.class);
                intent.putExtra("id","kim");
                intent.putExtra("pw",1234);
                intent.putExtra("person1",person1);
                startActivityForResult(intent,REQUEST_CODE);//결과를 받겠다


            }
        });

btnMain를 클릭 했을 때 서브화면으로 Intent를 통해 정보를 저장하여 전달한다.

 

정보를 저장 할 dto 객체를 생성 후

intent에 putExtra(key,value) 메소드를 이용하여 정보를 저장한다.

dto에는 생성자를 통해 css,3333 를 전달한다.

 

기본적인 화면을 넘길때는 startActivity를 사용하지만 정보를 저장 한 intent를 넘길 때는 

 

startActivityForResult(intent,REQUEST_CODE);//결과를 받겠다

 

를 사용한다.

 

-sub1.java-

 //데이터  받는 곳
        intent = getIntent();
        
        String id=intent.getStringExtra("id");
        int pw = intent.getIntExtra("pw",0); //INT값은 기본값을 주어야 한다.

        PersonDto person1 = (PersonDto) intent.getSerializableExtra("person1");  //serializable로 받음
        Log.d(TAG, "onCreate: id : "+id);
        Log.d(TAG, "onCreate: pw : "+pw);   //로그에는 int형을 단독으로 쓰지 못한다.

        tvSub1.setText("받은값은 : "+id+", "+pw);
        tvSub1.append("\nPerson1 : "+person1.getId()+", "+person1.getPw());
       // tvSub1.setText(tvSub1.getText()+"\nPerson1 : "+person1.getId()+", "+person1.getPw());

main에서 넘어온 intent를 sub1에서 넘겨받아 intent에 담겨진 정보를 꺼내서 저장 한다.

 

String id=intent.getStringExtra("id");
int pw = intent.getIntExtra("pw",0); //INT값은 기본값을 주어야 한다.

 

String형을 받을 때는 getStringExtra("key"),

Int 형을 받을 때는 getIntExtra("key"); 메소드를 사용한다.

 

PersonDto person1 = (PersonDto) intent.getSerializableExtra("person1"); //serializable로 받음

 

DTO객체를 받을 때는 직렬화 방식으로 받고 (personDTO)로 캐스팅을 해줘야 한다.

 

 

 //메인에 데이터 보내기
        btnSub1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent reintent = new Intent();
                reintent.putExtra("key",tvSub1.getText().toString()+" ㅋㅋㅋ");
                setResult(RESULT_OK,reintent); //메인에 결과를 보냄
                finish();   //엑티비티 종료
            }
        });

호출당한 엑티비티에서 호출한 엑티비티로 결과값을 전달 할 때는 setResult메소드를 사용한다.

finish(); 메소드를 통해 서브 엑티비티를 종료하고 메인 엑티비티로 돌아간다.

 

---전체코드---

더보기

-전체코드-

 

-main.xml-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
 >


    <Button
        android:id="@+id/btnMain"
        android:layout_width="151dp"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginStart="127dp"
        android:layout_marginLeft="127dp"
        android:layout_marginTop="62dp"
        android:layout_marginEnd="133dp"
        android:layout_marginRight="133dp"
        android:text="새화면띄우기" />

    <TextView
        android:id="@+id/tvMain"
        android:layout_width="171dp"
        android:layout_height="135dp"
        android:layout_below="@+id/btnMain"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginStart="119dp"
        android:layout_marginLeft="119dp"
        android:layout_marginTop="42dp"
        android:layout_marginEnd="121dp"
        android:layout_marginRight="121dp"
        android:text="TextView" />
</RelativeLayout>

-main.java-

package com.example.my10_intentresult;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button btnMain;
    TextView tvMain;
    public final int  REQUEST_CODE = 1004;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvMain=findViewById(R.id.tvMain);
        btnMain=findViewById(R.id.btnMain);

        btnMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PersonDto person1 = new PersonDto("css",3333);

                Intent intent = new Intent(MainActivity.this,Sub1Activity.class);
                intent.putExtra("id","kim");
                intent.putExtra("pw",1234);
                intent.putExtra("person1",person1);
                startActivityForResult(intent,REQUEST_CODE);//결과를 받겠다


            }
        });
    }

    // 데이터 받기

    @Override   //서브1에서 받는 부분
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode==REQUEST_CODE){     //1004이면
            if(data !=null){
             String key = data.getStringExtra("key");
             tvMain.setText(key);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}

-sub1.xml-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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=".Sub1Activity">

    <Button
        android:id="@+id/btnSub1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginStart="160dp"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="76dp"
        android:layout_marginEnd="163dp"
        android:layout_marginRight="163dp"
        android:text="메인으로 돌아가기" />

    <TextView
        android:id="@+id/tvSub1"
        android:layout_width="195dp"
        android:layout_height="90dp"
        android:layout_below="@+id/btnSub1"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginStart="107dp"
        android:layout_marginLeft="107dp"
        android:layout_marginTop="87dp"
        android:layout_marginEnd="109dp"
        android:layout_marginRight="109dp"
        android:text="TextView" />
</RelativeLayout>

-sub1.java-

package com.example.my10_intentresult;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Sub1Activity extends AppCompatActivity {
    private static final String TAG = "Sub1Activity";
    Button btnSub1;
    TextView tvSub1;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub1);


        btnSub1= findViewById(R.id.btnSub1);
        tvSub1 = findViewById(R.id.tvSub1);



        //데이터  받는 곳
        intent = getIntent();
        
        String id=intent.getStringExtra("id");
        int pw = intent.getIntExtra("pw",0); //INT값은 기본값을 주어야 한다.

        PersonDto person1 = (PersonDto) intent.getSerializableExtra("person1");  //serializable로 받음
        Log.d(TAG, "onCreate: id : "+id);
        Log.d(TAG, "onCreate: pw : "+pw);   //로그에는 int형을 단독으로 쓰지 못한다.

        tvSub1.setText("받은값은 : "+id+", "+pw);
        tvSub1.append("\nPerson1 : "+person1.getId()+", "+person1.getPw());
       // tvSub1.setText(tvSub1.getText()+"\nPerson1 : "+person1.getId()+", "+person1.getPw());


        //메인에 데이터 보내기
        btnSub1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent reintent = new Intent();
                reintent.putExtra("key",tvSub1.getText().toString()+" ㅋㅋㅋ");
                setResult(RESULT_OK,reintent); //메인에 결과를 보냄
                finish();   //엑티비티 종료
            }
        });

    }
}

-personDTO-

package com.example.my10_intentresult;

import java.io.Serializable;

public class PersonDto implements Serializable {
    String id;
    int pw;

    public PersonDto(String id, int pw) {
        this.id = id;
        this.pw = pw;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getPw() {
        return pw;
    }

    public void setPw(int pw) {
        this.pw = pw;
    }
}

 

'For developer > Android' 카테고리의 다른 글

(Android)my13_service  (0) 2020.05.21
(Android)my11_dialog_대화상자  (0) 2020.05.21
(my09_layoutinflate)인플레이트  (0) 2020.05.21
(Andorid)intentresult  (0) 2020.05.18
(Android)공모전 앱 제작(~ing)  (0) 2020.05.17

Inflate이란  xml 에 표기된 레이아웃들을 메모리에 객체화시키는 행동이다.

쉽게 말해서, XML 코드에 자바랑 연동해서 조작을 하기 위해서 사용한다.

 

 

 

 

 

더보기
package com.example.my09_layoutinflate;

        import androidx.appcompat.app.AppCompatActivity;

        import android.content.Context;
        import android.os.Bundle;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.widget.Button;
        import android.widget.LinearLayout;
        import android.widget.RelativeLayout;
        import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button btnMain ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnMain = findViewById(R.id.btnMain);
        btnMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout linear = findViewById(R.id.linear);
                RelativeLayout relative = findViewById(R.id.relative);

                LayoutInflater inflater =
                        (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                inflater.inflate(R.layout.sub1_layout,linear,true);
                inflater.inflate(R.layout.sub2_layout,relative,true);
                
                Button btnSub1 = linear.findViewById(R.id.button1);
                Button btnSub2 = relative.findViewById(R.id.button2);
                
                btnSub1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "리니어 버튼 클릭 !!!", Toast.LENGTH_SHORT).show();
                    }
                });

                btnSub2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "랠리티브 버튼 클릭 !!!", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="sub1버튼" />

    <CalendarView
        android:id="@+id/calendarView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="1dp"
        android:text="sub2 버튼" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginStart="154dp"
        android:layout_marginLeft="154dp"
        android:layout_marginTop="77dp"
        android:layout_marginEnd="148dp"
        android:layout_marginRight="148dp"
        app:srcCompat="@drawable/ic_launcher_foreground" />

    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginStart="99dp"
        android:layout_marginLeft="99dp"
        android:layout_marginTop="62dp"
        android:layout_marginEnd="72dp"
        android:layout_marginRight="72dp" />

    <SeekBar
        android:id="@+id/seekBar"
        style="@style/Widget.AppCompat.SeekBar.Discrete"
        android:layout_width="190dp"
        android:layout_height="91dp"
        android:layout_below="@+id/ratingBar"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="51dp"
        android:layout_marginEnd="98dp"
        android:layout_marginRight="98dp"
        android:max="10"
        android:progress="3" />
</RelativeLayout>

 

 

 

'For developer > Android' 카테고리의 다른 글

(Android)my11_dialog_대화상자  (0) 2020.05.21
(Android)my10_intentresult  (0) 2020.05.21
(Andorid)intentresult  (0) 2020.05.18
(Android)공모전 앱 제작(~ing)  (0) 2020.05.17
(Android)inflate  (0) 2020.05.15

+ Recent posts