앱을 만들어보다보니... 색상을 입히는 것도 테크니컬 해야 할 것 같은 생각이 들었다. 

쭈욱 작업을 하고 마무리를 하는 시점이 되었을 때 배경색을 변경해 달라고 하거나, 글짜색이 마음에 들지 않는 다고 한다. 흑~... theme 을 모르던 시절에는 하나하나 선택해서 font 도 지정하고 나름 color 도 지정해서 만들어 더니만.

이런이런... 

그럼 준비를 해 볼까 ?

먼저 theme.xml 을 이용해서 사용하고 싶은 style 을 만들어 본다.

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.Weroom714" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/default_color</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/white</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="android:fontFamily">@font/poorstory_regular</item>
        <item name="android:background">@color/default_color</item>
        <item name="android:windowBackground">@color/default_color</item>
        <item name="android:colorBackground">@color/default_color</item>
        <item name="android:textColor">@color/white</item>
        <item name="colorAccent">@color/softBlue</item> <!--  -->
        <item name="android:textColorPrimaryDisableOnly">@color/white</item> <!-- checkbox text color -->
        <item name="android:textColorSecondary">@color/softBlue</item>
        <item name="android:buttonTint">@color/white</item><!-- checkbox 의 체크상자 색상 -->
    </style>
    <style name="Theme.Weroom714.purple" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_200</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/white</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="android:fontFamily">@font/poorstory_regular</item>
        <item name="android:background">@color/purple_200</item>
        <item name="android:windowBackground">@color/purple_200</item>
        <item name="android:colorBackground">@color/purple_200</item>
        <item name="android:textColor">@color/white</item>
        <item name="colorAccent">@color/white</item> <!--  -->
        <item name="android:textColorPrimaryDisableOnly">@color/white</item> <!-- checkbox text color -->
        <item name="android:textColorSecondary">@color/softBlue</item>
        <item name="android:buttonTint">@color/white</item><!-- checkbox 의 체크상자 색상 -->
    </style>
    <style name="Theme.Weroom714.softBlack" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/softBlack</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/white</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="android:fontFamily">@font/poorstory_regular</item>
        <item name="android:background">@color/softBlack</item>
        <item name="android:windowBackground">@color/softBlack</item>
        <item name="android:colorBackground">@color/softBlack</item>
        <item name="android:textColor">@color/white</item>
        <item name="colorAccent">@color/white</item> <!--  -->
        <item name="android:textColorPrimaryDisableOnly">@color/white</item> <!-- checkbox text color -->
        <item name="android:textColorSecondary">@color/softBlue</item>
        <item name="android:buttonTint">@color/white</item><!-- checkbox 의 체크상자 색상 -->
    </style>
    <style name="Theme.Weroom714.darkBlue" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/darkBlue</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/darkBlue</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/white</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="android:fontFamily">@font/poorstory_regular</item>
        <item name="android:background">@color/darkBlue</item>
        <item name="android:windowBackground">@color/darkBlue</item>
        <item name="android:colorBackground">@color/darkBlue</item>
        <item name="android:textColor">@color/white</item>
        <item name="colorAccent">@color/white</item> <!--  -->
        <item name="android:textColorPrimaryDisableOnly">@color/white</item> <!-- checkbox text color -->
        <item name="android:textColorSecondary">@color/softBlue</item>
        <item name="android:buttonTint">@color/white</item><!-- checkbox 의 체크상자 색상 -->
    </style>
    <style name="Theme.Weroom714.darkGreen" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/darkGreen</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/darkGreen</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/white</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="android:fontFamily">@font/poorstory_regular</item>
        <item name="android:background">@color/darkGreen</item>
        <item name="android:windowBackground">@color/darkGreen</item>
        <item name="android:colorBackground">@color/darkGreen</item>
        <item name="android:textColor">@color/white</item>
        <item name="colorAccent">@color/white</item> <!--  -->
        <item name="android:textColorPrimaryDisableOnly">@color/white</item> <!-- checkbox text color -->
        <item name="android:textColorSecondary">@color/softBlue</item>
        <item name="android:buttonTint">@color/white</item><!-- checkbox 의 체크상자 색상 -->
    </style>
    <style name="Theme.Weroom714.Loading" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:background">@color/default_color</item>
        <item name="android:windowBackground">@color/default_color</item>
        <item name="android:colorBackground">@color/default_color</item>
        <item name="colorPrimary">@color/default_color</item>
        <item name="android:textColor">@color/softBlue</item>
        <item name="android:fontFamily">@font/poorstory_regular</item>
    </style>
    <style name="ButtonText" parent="@android:style/Widget.Button">
        <item name="android:textColor">@color/white</item>
        <item name="android:background">@drawable/background_btn</item>
    </style>
    <style name="CustomRadioButton" parent="Theme.AppCompat.Light">
        <item name="colorAccent">@color/white</item>
        <item name="colorControlNormal">@color/default_color</item>
    </style>
    <style name="Theme.Weroom714.Transparent" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:textColor">@color/softBlue</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowAnimationStyle">@android:style/Animation</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="android:fontFamily">@font/poorstory_regular</item>
    </style>
    <style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorAccent">@color/softBlue</item>
        <item name="android:textColor">@color/softBlue</item>
        <item name="android:textColorPrimary">@color/white</item>
        <item name="android:background">@color/default_color</item>
    </style>
</resources>

이렇게 길어야 하는 생각이 들기는 하지만, 아직 조금의 미숙(?)함이 있는 관계로 다가 비슷한 sylte 을 복사해서 여러개 만들었다.

기본테마 Theme.Weroom714 부터 Theme.Weroom714_darkGreen, Theme.Weroom714_darkBlue, Theme.Weroom714_softBlack 까지 사용자는 4개의 색상 조합을 요청했다.  자세히 살펴 보면 다른 건 없고, 배경색만 다르게 지정하는 구성이다. 

이걸 어떻게 지정하는 건가 ?

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = getSharedPreferences(getPackageName(), MODE_PRIVATE);
        if (sp.getString("THEME", "default_color").equals("darkBlue")) {
            setTheme(R.style.Theme_Weroom714_darkBlue);
        } else if (sp.getString("THEME", "default_color").equals("darkGreen")) {
            setTheme(R.style.Theme_Weroom714_darkGreen);
        } else if (sp.getString("THEME", "default_color").equals("softBlack")) {
            setTheme(R.style.Theme_Weroom714_softBlack);
        } else {
            setTheme(R.style.Theme_Weroom714);
        }
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot() ;
        setContentView(view);
        
  }

적용하려는 activity 의 onCreate 에 위와 같이 적용하면 된다. 여기서 주의할 것은 viewBinding 을 하고 있기 때문에 그 위치를 잡는데, 테스트를 몇차례해서 정한건데, layout 을 binding 하기전에 setTheme()을 이용해서 먼저 설정하고 binding을 해야 실행 했을때 적용이 되는 것을 확인할 수 있었다.

이렇게 선택적으로 배경색을 변경하는 앱을 만들어 볼 수 있었다.

 

오늘도 즐~ 코딩...

 

p.s 이 미숙함을 지적해 주실꺼면 아래 댓글로 부탁 드립니다. 꾸벅^^;;

반응형

앱을 하나 만들다 보니.... 전체 화면에 보일 수 있도록 만들어 달라는 요청이 있네... 어떻게 하나 ?

구글님에게 질문을 해 본다... 그러고선 이렇게 구현을 해 보았다.

    @Override
    protected void onPostResume() {
        super.onPostResume();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                hideSystemUI();
            }
        }, 500);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }

    private void hideSystemUI() {

        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                          View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        decorView.requestLayout();
    }

 

먼저 activity 의 lifecycle 을 대해서 찾아볼 필요가 있다. 왜 그런가 하면 액티비티가 생성되면서 어느 시점에 화면을 다시 그리게 할 것인가를 정해야 할 것 같아서 이다.  개발자 페이지에서 받아온 이미지 하나를 링크을 달았다.

저 그림의 순서을 보면 onCreate 나 onStart 에 화면 다시 그리기를 넣어 놓으면 처음 실행할 때는 적용이 되겠지만, 다른 액티비티로 갔다가 돌아올때는 실행이 되지 않는 다, 그래서 혹시나, 이 액티비티에서 다른 액티비티를 호출했다가 돌아와야 하는 경우가 있다면 필수적으로 onResume에 넣어 주는 것이 좋을 것 같다.

이미지 출처 : https://developer.android.com/guide/components/activities/activity-lifecycle

 

그리고 위의 소스에서 onWindowFocusChanged 는 구글링에서 나온 부분일껀데, 아마도 윈도우가 다시 활성화 되는 시점에 처리를 하고 넣은 게 아닐까 ? 

뭐 아무튼 이렇게 처리를 하게 되면 앱이 실행되고 나서 화면 전체를 차지하게 된다.

내가 만든 앱 실행화면

이런식으로 위/아래 있는 상태바, 네비게이션바등이 다 숨어지게 된다.

 

끝.

반응형

 

집에 오는 길에... 길가에 있던 들꽃 

이름은 무엇인가 ?

날이 더운데 잘 지내는 지 ?

오늘 하루도 좋은 하루가 되었길 바라며...

다음에 다시 만나게 되면 더 좋은 이야길 할 수 있게 되길 바라며...

반응형

'그냥글쓰기' 카테고리의 다른 글

들꽃  (0) 2021.08.04
어부바 귀요미  (0) 2021.08.03
망부석(?) 개인형 이동장치  (0) 2021.07.01
들꽃2  (0) 2021.06.30
"나는 자는동안에도 돈을 번다" 책을 듣고 나서 (feat 윌라오디오북)  (2) 2021.06.30

앱을 만들다가... 갤러리에서 이미지 받아오는 와서 사용하는 것을 구현하고 있는 중인데...

사진이 돌아간다. 흑~ 그래서 구글링 신에서 질문을 했다...

답... Exif 을 구현해서 사진을 돌리는 코드가 나오고... 

그것 보다는 조금 간결한 코드 구현 방법이 보인다.

http://bumptech.github.io/glide/doc/getting-started.html

 

Glide v4 : Getting Started

Basic Usage Loading images with Glide is easy and in many cases requires only a single line: Glide.with(fragment) .load(myUrl) .into(imageView); Cancelling loads you no longer need is simple too: Glide.with(fragment).clear(imageView); Although it’s good

bumptech.github.io

glide 이건 뭔가 ???  쉬운 이미지 처리 방법 

 

백그라운드 스레드
배경 스레드에 이미지를 로드하는 것도 submit(int, int)다음을 사용하여 간단합니다 .

FutureTarget<Bitmap> futureTarget =
  Glide.with(context)
    .asBitmap()
    .load(url)
    .submit(width, height);

Bitmap bitmap = futureTarget.get();

이렇게 설명된 부분을 참조 하면 될 것 같다. 또 하나 방법은 바로 imageView 에 넣는 방법인데...  

알고 싶은 건 Bitmap 에 값을 넣는 것이니... 그런데... 백그라운드 스레드로 해야 한다는 부분을 주의 해야 했다.

그래서 아래 처럼 코딩해서 해소 끝...

            FutureTarget<Bitmap> futureTarget =
                    Glide.with(getApplicationContext())
                            .asBitmap()
                            .load(photoUri)
                            .submit(width, height);

            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    try {
                        Bitmap bitmap = futureTarget.get();

                        GroupImageBean bean1 = new GroupImageBean();
                        bean1.setImageGrpId(groupName);
                        bean1.setImageData(bitmap);
                        bean1.setOriginalUri(photoUri);
                        bean1.setImageUri(photoUri);
                        bitmapArrayList.add(bean1);

                        dbHandler = DBHandler.open(SetGroupActivity.this);
                        dbHandler.insertImage(bean1);
                        dbHandler.close();

                        getAdapterUpdateReceiptsList();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }, 660);

 

다음에 또 이런걸 하게 될 지 모르지만... 

 

아래 코드는 갤러리에서 사진 선택할 수 있도록 호출 하기 위한 코드 ...

 

                Intent intent = new Intent();
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) // 이건 동시에 여러장 선택
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, REQUEST_CODE);

저렇게 호출하면 그걸 받아서 처리하는 부분은 

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if(requestCode == REQUEST_CODE)
        {
            if(resultCode == RESULT_OK)
            {
                try{
                    InputStream in = getContentResolver().openInputStream(data.getData());

                    Bitmap img = BitmapFactory.decodeStream(in);
                    in.close();

                    imageView.setImageBitmap(img);
                }catch(Exception e)
                {

                }
            }
            else if(resultCode == RESULT_CANCELED)
            {
                Toast.makeText(this, "사진 선택 취소", Toast.LENGTH_LONG).show();
            }
        }
    }

이렇게 activity 호출 결과를 받아서 처리하면 됨...

오늘 도 즐~~~ 코딩...

반응형

앱을 하나 만들고 있는 중인데, 

하다 보니  중복이 없는 random 값을 추출해야 하는 고민에 빠짐... 

와이프님의 백신 예약도 해야 하는 날인데,  예약 서버는 버벅 거리고... 나의 머리도 버벅 거리고...

우째 우쨰 드뎌 완성!!!

아래 소스는 간단히 설명 하자면... 사용하기 위해서는 우선 

import java.util.Random; 

이 필요하다...  그리고 아래 나열된 부분은 함수 부분만 적었으니, 어딘가에서 호출하는 부분도 있어야 할 것 같다.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        ...
        int[] dispOrder = getRandomCount(iTyCnt);
        ...
        
    }

뭐 이런식으로 다가...  getRandomCount 로 넘어가는 파라미터인 count 는 추출해야 하는 숫자의 제일 큰 값 이라고 

보면 된다.  물론 시작하는 숫자는 0 이고. 그래서 0 ~ count 범위 내에서 random 한 숫자를 만들어서 

결과로 돌려 주는 것이다.

    /**
     * 중복이 없는 랜덤한 숫자 만들기
     * @param count
     * @return
     */
    public int[] getRandomCount(int count) {
        int[] nResult = new int[count];

        for(int i=0; i < count; i++) {
            if (i == 0) {
                nResult[i] = getRandomValue(count) ;
            } else {
                nResult[i] = getRandom(i, count, nResult); // 배열 사용을 위해서 -1 했음.
            }
            Log.e(TAG, "------[" + i + "]=" + nResult[i]) ;
        }

        return nResult ;
    }

    /**
     * 재귀호출을 통해서 중복이 없는 숫자를 만든다.
     * @param ii : 선택된 위치
     * @param count : 제일 큰 값의 범위
     * @param nResult : 결과를 저장하는 배열
     * @return
     */
    private int getRandom(int ii, int count, int[] nResult) {

        int randomValue = getRandomValue(count) ;
        for(int i = 0 ; i < ii ; i++) {
            //Log.e(TAG, "nnn [" + i + "]=" + "<" + ii + ">" + nResult[i] + "==" + randomValue) ;
            if (randomValue == nResult[i]) {
                randomValue = getRandom(ii, count, nResult) ;
                break;
            }
        }
        return randomValue ;
    }

    /**
     * 랜덤하게 숫자를 하나 만듬
     * @param count : 제일 큰 값의 범위
     * @return
     */
    private int getRandomValue(int count) {
        Random random = new Random();
        return random.nextInt(count);
    }

 

궁금한 부분이 있다면  아래 댓글로 달아 두시면 답을 적어 드립니다.

 

반응형

앱을 만들어 등록하는 동안 하고 싶은 것 중에서 한가지는 여러나라의 언어로 배포를 해 보는 것이였다. 예전에는 그걸 하나 하나 번역을 해 가면서 등록을 했던 것을 카카오 번역 API 호출하여 사용하는 방법으로 해소해 보자.

일단, 목적으로 하는 앱을 만드는 과정을 했다고 치고. 기본 언어를 영어(아니면 한국어도 상관 없이)로 하고 앱을 만든다음 android studio 에서 번역을 하기 위한 준비를 해 보자.

언어 번역을 위해서 Translations Editor 을 열어 아이콘 중에서 지구모양 아이콘을 클릭 하면 어떤 언어를 선택할 것이지 정할 수 있다.  그것중에서 일단, 영어, 한국어, 일본어, 베트남어 (2022년 월드컵 예선 진출을 응원하며 ...) 선택해서 만들어 보기로 했다.

영어 버전을 예시로 하기 위해서 샘플은 영어 버전 string.xml 을 표시해 본다.

 

 

 

 

이제 번역은 어떻게 할 것인가 ?

카카오 개발자 페이지 (https://developers.kakao.com/console/app) 에서 새 어플리케이션을 등록하고

 

팝업창에서 앱이름, 사업자명 (없으면 우리집 이렇게라도)

입력하고 저장하기를 하면 되고

 

 

 

 

앱키를 취득하면 준비는 일단 완료된 것이다

이중에서 우리는 REST API 을 이용할 것이기 떄문에

REST API 키를 기억하고 있으면 된다.

 

 

 

다음은 python 을 이용할 것인데, python 의 설치 등등에 관한 것은 구글링을 통해서 많이 볼 수 있으므로 여기서는 생략해 본다.

참고로 python 을 작업하는 것도 pycham 이라는 툴을 사용하고 있는데, 이것에 대한 설명도 생략하므로 참고하시길

import requests

# 카카오 API 번역 호출
def translate(StringValue):
    url = "https://dapi.kakao.com//v2/translation/translate"
    headers={ "Authorization" : "KakaoAK f57a4f***********5006481"}
    data = {"query" : StringValue, "src_lang" : "en", "target_lang" : "jp"}

    response = requests.get(url, headers=headers, params=data)

    if response.status_code == 200:
        return response.json()["translated_text"]

# android string.xml 을 이용한 번역하기
def getString(lines):
    line = lines.split(">")
    try:
        s1 = translate(line[1].split("<")[0])
        s = str(line[0]) + ">" + str(s1[0][0]) + "<" + str(line[1].split("<")[1]) + ">"
        return s
    except:
        return lines

# 내앱의 영문 기준 스트링 파일
f = open("C:/workspaces/Bo****26/app/src/main/res/values/strings.xml", 'r')
while True:
    line = f.readline()
    if not line: break
    if 'translatable' in line:
        pass
    else:
        print(getString(line))

f.close()

먼저 python 에서 기동할 소스인데,  주의할 것은 headers 에 있는 API KEY 

headers={ "Authorization" : "KakaoAK f57a4f***********5006481"} 에서 f57a... 부분은 여러분이 받은 키값으로 변경해야 하며 

아래 부분에 open 에서 사용하는 파일도 여러분이 작성한 strings.xml 파일의 경로를 지정해 주어야 한다. 이 예시는 영문을 기준으로 변환을 하는 것이라서 저 소스상에 있는 src_lang 가 en 으로 되어 있으니 한국어를 기준으로 하려면 kr 로 변경해야 한다. 

카카오에서 지원해주는 번역에서 언어표기는 아래 표시된 정도이니 참고해서 사용하면 된다. src_lang 에는 원본 target_lang 에는 번역하고 싶은 언어 표기로 설정해 주면 된다. (https://developers.kakao.com/docs/latest/ko/translate/common)

한국어 kr
영어 en
일본어 jp
중국어 cn
베트남어 vi
인도네시아어 id
아랍어 ar
뱅갈어 bn
독일어 de
스페인어 es
프랑스어 fr
힌디어 hi
이탈리아어 it
말레이시아어 ms
네덜란드어 nl
포르투갈어 pt
러시아어 ru
태국어 th
터키어 tr

 

이제 실행을 해보면 아래 예시 그림과 같이 번역이 되어 나오는 것을 볼 수 있다.

이 내용을 그대로 android studio 에서 생성된 일본어 strings.xml 에 붙여 넣으면 번역 끝.

다만, 직역을 하기 때문에 그 나라에 사시는 분들이 이해를 하는 데, 도움이 될까는 조금 고민해 볼 필요가 있을 것 같기는 하다.

이것으로 다국적(?)앱 만들어 끝!!!

반응형

아침 출근길에 만난...
몇날 몇일을 이곳에 버려진(?) 망부석 처럼

이것들은 일상에 이로운 것인가?
해로운 것인가?

그렇다고해서 선뜻 탈 수도 없다.
과태료 때문에...

반응형

'그냥글쓰기' 카테고리의 다른 글

어부바 귀요미  (0) 2021.08.03
둘꽃  (0) 2021.07.24
들꽃2  (0) 2021.06.30
"나는 자는동안에도 돈을 번다" 책을 듣고 나서 (feat 윌라오디오북)  (2) 2021.06.30
들꽃 (feat 날좋은 휴일 오후)  (0) 2021.06.29

들꽃2

집으로 오는길에...
인도 한 켠에 핀 들 꽃
예전에는 산을 오르거나 했어야 보아았던...

이제  여름이  가고나면
다 떠날까???

반응형

python 이나, java 에서 소스를 이용해서 jsoup 파싱을 해 보기는 했으나,  android 폰에서 구현하는 파싱은 이번이 처음이다. 

예전에 lotto 당첨 결과를 얻어오는 앱을 만들어 본 적이 있는데, 

그때는 정말 날코딩으로 html 페이지를 분석해서 쪼개여 왔는데, 이제 그 보다 쉬운 방법이 있다는 것이다. 

동행복권 페이지에서 회차별 당첨 결과를 조회하는 페이지를 열어서 F12(개발자도구)을 이용해서 페이지에서 얻어와야 하는 html tag 을 찾아보자. 

다음은 android studio 에서 새 프로젝트를 하나 만들고... 제일 먼저 그래드 설정에 다음과 같이 jsoup 사용을 위해 추가해 본다. (2021.06.30 기준 버전은 1.13.1)

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'org.jsoup:jsoup:1.13.1'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

그 다음은 manifast 파일을 열어서 인터넷 사용을 위한 권한 설정을 한다.

    <uses-permission android:name="android.permission.INTERNET" />

그리고 다음은 화면을 그릴껀데, 이건 예제 이므로 단순하게  버튼 하나와 textView 하나만 담았다.

<?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=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/button"
        android:scrollbars="vertical"
        android:text="" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="22dp"
        android:layout_marginBottom="43dp"
        android:text="HTML 가져오기" />

</RelativeLayout>

 

그리고 이번에는 MainActivity 구현을 해 본다.

소스에서 살펴볼 부분은 AsyncTask 을 이용해서 비동기 통신을 해야 한다는 것과  어떻게 하면 결과 숫자값만 뽑아올 수 있는 가 하는 부분이다.  위에 html 결과에서 span tag 을 값을 받아와야 하는 데 class 만 표시 되어 있어서 그 class 의 공통적인 종류를 이용해서 필요한 부분이 결과만 추출해 오면 된다.

package com........;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private String drwNoUrl = "https://dhlottery.co.kr/gameResult.do?method=byWin";
    private TextView textviewHtmlDocument;
    private String htmlContentInStringFormat = "";
    private String nowCnt = "" ;
    String TAG = "Lotto" ;

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

        textviewHtmlDocument = (TextView) findViewById(R.id.textView);
        textviewHtmlDocument.setMovementMethod(new ScrollingMovementMethod());

        Button htmlTitleButton = (Button) findViewById(R.id.button);
        htmlTitleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                nowCnt = "969"; // 2021.06.30 기준 마지막 회차
                JsoupAsyncTask jsoupAsyncTask = new JsoupAsyncTask();
                jsoupAsyncTask.execute(drwNoUrl, nowCnt);

            }
        });
    }

    // 백그라운드 호출을 해야 하는 것은 실시간으로 답을 받아올 수 없기 때문에
    private class JsoupAsyncTask extends AsyncTask<String, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... params) {
            Log.i(TAG, Arrays.toString(params));
            try {
                // 파라미터로 넘어온 값을 이용해서 url 와 회차를 설정한다.
                String callUrl = params[0] + "&drwNo=" + params[1];
                Document doc = Jsoup.connect(callUrl).get();
                // 위의 html tag에서 결과숫자를 싸고 있는 span tag 을 class명을 이용함.
                Elements links = doc.select(".ball_645");
                Log.e(TAG, "links=" + links.size());
                htmlContentInStringFormat += "회차=" + nowCnt ;
                for(Element el : links) {
                    Log.e(TAG, el.text()) ;
                    htmlContentInStringFormat += " " + el.text() ;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            textviewHtmlDocument.setText(htmlContentInStringFormat);
        }
    }    
}

AsyncTask를 사용하면 UI 스레드를 적절하고 쉽게 사용할 수 있다. 이 클래스를 사용하면 스레드 및 / 또는 핸들러를 조작하지 않고도 백그라운드 작업을 수행하고 UI 스레드에 결과를 게시 할 수 있다.

AsyncTask는 Thread and Handler에 대한 도우미 클래스로 설계되었으며 일반적인 스레딩 프레임 워크를 구성하지 않는다. AsyncTasks는 짧은 작업 (최대 몇 초)에 이상적으로 사용되어야 한다.

화면의 결과가 초라해(?) 보이기는 해도 쉽게 그 결과를 얻어올 수 있었다.

 

살펴보고 궁금한 것이 있으시다면.  댓글을 달아 주세요.

반응형

윌라오디오북을 듣고 나서 ... 어떻게 이런 생각을 하고 사는 걸까 ?
조금은 일찍 알았다면, 좋았을까 하는 생각이 드는건 왜인가 ? 그래도 시작이 반이라는 말 처럼
이제라도 시작해 보면 언제가 좋은 날이 올 수 있는 것인가 ?
세상에 공짜는 없다는 말이 맞는 것 같다. 그래서 이책 저자의 말이 맞는 말이기도 하지만,
사실 절대적으로 맞는 말은 아니다. 그 또한 노력의 결과로 받아 드려져야 하는 것이라고 생각이 든다.
그래도 배운건 있지. 어떻게 하면  광고판을 얻을 수 있는 가 하는 것...

구글 애드센스 도전을 하고 있는데, 그쪽에서 받은 메일은 다음과 같다.

광고 게재가 준비되지 않은 사이트
사이트에서 정책 위반이 발견되어 아직 광고를 게재할 수 없습니다.

가치 있는 인벤토리: 콘텐츠 없음
Google에서는 콘텐츠가 없는 경우 수익 창출을 허용하지 않습니다.

제작 중인 사이트 또는 앱에 대한 자리표시자 콘텐츠를 포함하는 콘텐츠가 없습니다.
자세한 내용은 다음 자료를 참조하세요.

사이트에서 고유 콘텐츠와 우수한 사용자 환경을 제공하는지 확인하기
고품질 사이트를 만들기 위한 정책 도움말 2부
웹마스터 품질 가이드라인

콘텐츠 정책을 확인하거나 고객센터를 방문하여 자세한 정보를 확인하세요. 위반사항을 수정했으면 사이트 검토를 요청할 수 있습니다.

콘텐츠가 없음... 이게 무슨말인가 ? 내 딴에는 나름 이런 저런 것들도 열댓개의 글을 게시했는데, 말이지... 물론 내용이 써 많은 것은 아니지만... 그리고 더 자세한 가이드를 해 주지 않는다. (설령 내가 찾지 못한 것일 수 도 있지만)

이책의 내용을 듣다 보면  최소 1500자 이상의 글을 적은 페이지가 30개 이상은 되어야 할 것 같은 생각이 들었다. 그래서 그동안 적어 두었던 페이지를 살펴 보니 나름 이해가 안되는 것인 아니였다. 그런다고 해서 내가 뭘 더 채울 수 있는 것인가 하는 부분에 대해서는 고민을 해 보지 않을 수 없었다.  그래서 아직도 난 애드센서의 허가(?)을 얻지 못하고 있는 중이고, 어느날은 얻을 수 있을 지 모르겠지만 서도...

또 하나 잊혀지지 않아야 하는 주제는 파이프라인 을 만들어야 한다는 말...  이런 저런 것들을 차곡 차곡 쌓아두다 보면 나중에는 도움이 되는 길이 생길까 하는 것? 아직은 그것에 대해서 알 수는 없으나... 어느 날에는 아는 날이 올까 하는 궁금함이 생긴다.   이글은  이책의 저자가 말한 편법(?)을 누리는 중이다. 혹시 이해가 되지 않는 다면... 이 책을 꼭 읽어 보시길... ㅋㅋㅋ

이책의 목차는 아래와 같다.

추천의 글
리남의 강의를 수강한 분들의 실제 후기

프롤로그
지극히 평범했던 나도 했기 때문에
당신도 할 수 있습니다

제1부 원하는 것을 이루는 부의 마인드셋
01 돈을 벌기 위해 취업을 포기했다
나는 N포세대다
탈선도 필요할 때가 있다
바뀌고자 한다면 행동이 우선이다
나 자신을 알기로 했다

02 나는 자면서도 돈을 벌기로 결심했다
의심을 확신으로 전환하라
온라인은 모든 게 돈이다
당신도 같은 실수를 하고 있을지 모른다
도움 없이 스스로 시작하는 방법

03 무자본으로 파이프라인을 구축하라
월급은 노후를 보장하지 않는다
죽는 순간까지 물을 길을 수는 없다
*부업을 하는 이유: 파이프라인
무자본, 최소 시간, 공간 제약이 없는 가장 현실적인 부업
*취미로 돈을 버는 가장 현실적인 방법
파이프라인 구축을 위해 필요한 것

04 거창하지 않아야 시작할 수 있다
블루오션을 찾지 않기로 했다
블로그는 이제 끝났다는 모두의 거짓말
*블로그로 돈 버는 시대는 끝났다?
사실 거창한 이유는 필요 없다

05 실수를 반복하지 않기로 다짐했다
실패를 통해서도 배울 게 있다
처음에 돈을 벌지 못했던 이유
*블로그로 돈을 벌기 위해 필요한 것
그때는 몰랐고, 지금은 알게 된 것
여우와 두루미가 내게 준 교훈

제2부 자면서도 돈이 들어오는 파이프라인 구축 공식
01 성공의 핵심은 극비의 노하우가 아니다
근본적으로 필요한 것
온라인 마케팅으로 돈을 버는 방법
*인터넷 광고 종류 정리
반드시 알아야 할 마케팅 플랫폼

02 딱, 아는 만큼 보인다
블로그 서비스의 종류와 특징
*수익형 블로그 어디서 만들까?
*워드프레스 정말 저품질이 없을까?
애드센스를 선택한 이유
아는 것과 모르는 것의 차이
*블로그 월 1000만 원 수익 공개

03 첫 단추를 제대로 끼우는 게 중요하다
시작이 반이다
티스토리 블로그 사용법
*수익형 블로그 최적화 세팅
*티스토리 신규 에디터 사용법
검색되는 블로그를 만들자
*블로그 검색 등록 하는 방법

04 시작은 구글 애드센스로 하라
구글 애드센스 승인 TIP: 정공법과 편법
구들 애드센스 신청하기
*구글 애드센스 승인받기
구글 애드센스 사용법
*애드센스 광고 넣는 방법

05 어떻게 나만의 무기를 갖는가
나만의 효과적인 무기를 갖는 방법
*블로그 주제 선정 TIP
*키워드 추출 방법 

https://www.welaaa.com/audio/detail/7680

 

나는 자는 동안에도 돈을 번다

저자 소개 빠듯한 가정에서 태어나 그 누구보다 평범하고 현실적인 삶을 추구하던 취준생이었지만, 대학 졸업 후 돌연 취업 포기를 선언했다. 내 집 마련, 결혼과 육아 등 월급의 한계가 가져다

www.welaaa.com

 

p.s (2021.07.06)

바라면 이루어 지는 건가... 드디어 오늘 메일 받았다.. adsense 로 부터... 드디오 광고를 허 하노라...

반응형

'그냥글쓰기' 카테고리의 다른 글

어부바 귀요미  (0) 2021.08.03
둘꽃  (0) 2021.07.24
망부석(?) 개인형 이동장치  (0) 2021.07.01
들꽃2  (0) 2021.06.30
들꽃 (feat 날좋은 휴일 오후)  (0) 2021.06.29

+ Recent posts