구글맵 (GoogleMap) 출력을 위한 인증 코드 생성, 활용

프로그래밍/Android (Java)|2019. 5. 14. 14:20
반응형

아래 두개 웹페이지만 참고해도 적용이 가능합니다.

https://mailmail.tistory.com/17

https://webnautes.tistory.com/647

 

 

 

=== 실제 작업 순서 ===

 

https://console.firebase.google.com/ 에서 해당 프로젝트 선택 후

좌측 상단의 '톱니바퀴' 모양 클릭 > '사용자 및 권한' 선택

 

[일반] 탭 선택 후 하단의 'SHA 인증서 지문' 에 '디지털 지문 추가' 선택

 

윈도우즈 cmd 에서 아래 명령으로 출력된 SHA-1 부분을 복사, 붙여넣고 생성하기

 

cd C:\Program Files\Android\Android Studio\jre\bin

 

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

 

프로젝트 상세 내용 변경 되었으므로 google-services.json 파일 새로 갱신 (다운로드, 적용)

 

https://console.developers.google.com/apis/dashboard 에서 해당 프로젝트 선택 후 (맨위)

'+ API 및 서비스 사용 설정' 을 눌러 'Maps SDK for Android' 검색, 사용 설정

[사용자 인증 정보] 탭 선택 후 '사용자 인증 정보 만들기'.. 위에  API 관리자의 사용자 인증 정보 링크 부분 타고 들어감

상단에 다시 '사용자 인증 정보 만들기' 선택 후 출력된 'API 키' 선택

- 애플리케이션 제한 사항 : Android

- Android 앱의 사용량 제한 : firebase 에서 생성한 프로젝트명 (예: kr.itlog.makchatime) 과 SHA-1 키입력

- API 제한 사항 : 키제한 ('Maps SDK for Android' 선택)

- SAVE

 

개발중인 AndroidManifest.xml 파일의 <application> 안에 아래 내용 추가

---------------

<meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyD.......키 보안상 생략........CoLOlk" />

---------------

 

이제 준비가 되었으므로 예제 소스코드를 검색, 적용하여 확인하면 됩니다.

 

 

*참고로 화면이 하얗게 뜨는것은 인증이 되지 않아서 이므로 위 과정을 다시 살펴봐야 함.

 

 

 

 

 

 

 

 

반응형

댓글()

ScaleAnimation 사용하기

반응형

이미지나 막대그래프 등이 늘어나고 줄어드는 등의 효과를 보여줄 수 있습니다.

 

layout 에서 적용

https://bitsoul.tistory.com/82

 

source 에서 적용

https://bitsoul.tistory.com/83

 

 

 

반응형

댓글()

Custom listview (Parse JSON And URL Images) - 웹 이미지

프로그래밍/Android (Java)|2019. 4. 30. 13:01
반응형

https://demonuts.com/android-parse-json-and-show-in-listview/

 

Json_Parse_Listview.zip
2.07MB

 

* 소스 말고 포스팅 글을 가지고 셋팅한다면 중간에 오타를 잘 살펴볼것

- 레이아웃명 : lv_players

- 소스에서 연결 : lv_player

 

* 예제는 해외 url 을 가져오므로 느림. 국내 서버에 json 파일과 이미지를 링크시키면 빠름

 

* 리스트뷰 아이템 클릭시 이벤트 발생 시키고 싶을 경우 아래 소스를 TennisAdapter.java 파일의

return convertView; 바로 위에 넣고 상황에 맞게 수정해 쓸 것.

 

        // 넘버링

        final int pos = position;

        // 위젯에 대한 이벤트 리스너

        holder.iv.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(context, "이미지 선택 " + pos, Toast.LENGTH_SHORT).show();

            }

        });

        holder.tvname.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(context, "이름 선택 " + pos, Toast.LENGTH_SHORT).show();

            }

        });

        holder.tvcountry.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(context, "나라 선택 " + pos, Toast.LENGTH_SHORT).show();

            }

        });

        holder.tvcity.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(context, "도시 선택 " + pos, Toast.LENGTH_SHORT).show();

            }

        });

 

 

반응형

댓글()

커스텀 리스트뷰 (Custom ListView) - 로컬 이미지 + 텍스트 (ArrayList)

프로그래밍/Android (Java)|2019. 4. 24. 12:21
반응형

Activity, Fragment 에서 동일하게 적용 가능한 소스 입니다.

Fragment 에서 사용시 build 할때 getApplicationContext() 부분에 에러가 출력된다면 아래와 같이 사용하세요.

 

getActivity().getApplicationContext()

 

==============================================

 

기본적인 커스텀 리스트뷰

https://mailmail.tistory.com/6

 

항목 선택시 이벤트 발생 (추가분)

https://mailmail.tistory.com/8

 

* 이미지를 웹에서 가져오는거는 별도 소스 찾아봐야 함

 

반응형

댓글()

RelativeLayout 과 view 정렬의 실 사용 예

프로그래밍/Android (Java)|2019. 4. 23. 15:18
반응형

activity_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">


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
          android:layout_above="@id/status_bar">  // 상대 id 를 이용하여 정렬을 한다.

        <TextView
            android:id="@+id/notice"
            android:layout_width="match_parent"

            android:layout_height="wrap_content" />

    

    </ScrollView>


    <LinearLayout
          android:id="@+id/status_bar"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:background="#F6FFCC"
        android:gravity="center"
        android:orientation="horizontal"
          android:layout_alignParentBottom="true" // 해당 부분을 맨 아래에 붙인다.
          android:layout_alignParentLeft="true"> // 해당 부분을 맨 좌측에 붙인다.
        
        <TextView
            android:id="@+id/user_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:text="AD Block + 7 / Search" />
        
    </LinearLayout>

 

</RelativeLayout>

 

반응형

댓글()

스피너 사용하기 (셀렉트박스 selectbox, 풀다운 메뉴)

프로그래밍/Android (Java)|2019. 4. 23. 11:03
반응형

스피너를 사용하며, 보여지는 제목 및 터치시 출력되는 세부 아이템에 줄간격, 폰트 사이즈, 라인 효과를 주는 방법입니다.

 

 

1. activity_main.xml

 

<Spinner
                android:id="@+id/spinner"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="45"
                android:textSize="14sp"
                android:layout_centerHorizontal="true"/>

 

 

2. MainActivity.java

 

public class Fragment2 extends Fragment {

 

    private Spinner spinner;
    ArrayList arrayList;
    ArrayAdapter arrayAdapter;

 

 

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

 

 

        arrayList = new ArrayList<>();
        arrayList.add("네이버");
        arrayList.add("다음");

        arrayAdapter = new ArrayAdapter(getActivity().getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, arrayList) {

               // 누르기 전 보여지는 기본 폰트 스타일
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView tv = (TextView) view;
                tv.setTextSize(14);
                return view;
            }

               // 누른 뒤 출력되는 리스트 폰트 스타일
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = super.getDropDownView(position, convertView, parent);
                TextView tv = (TextView) view;
                if(position == 0) {
                    tv.setTextColor(Color.GRAY); // 포지션 0 에 제목을 넣었으므로 흐리게 표현한다.
                    tv.setTextSize(14);
                }
                else {
                    tv.setTextColor(Color.BLACK);
                    tv.setTextSize(14);
                    tv.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.textlines)); // 아이템 상단에만 라인 생기도록 하였음 (첫번재 아이템 제외)
                }
                return view;
            }

        };

        arrayAdapter.setDropDownViewResource(R.layout.spinner_item); // 스피너 디자인 (폰트크기, 사이즈, 줄간격 등) 을 바꾸기 위해 별도 xml 파일 만듬

        spinner = (Spinner) view.findViewById(R.id.spinner);
        spinner.setAdapter(arrayAdapter);
        spinner.setSelection(choice_spinner, false); // 처음 페이지를 열었을때는 동작하지 않도록 설정 (false 부분) // choice_spinner 는 int
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            // 아이템을 선택한 경우 이벤트
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                  Toast.makeText(getActivity().getApplicationContext(), i + "선택", Toast.LENGTH_SHORT).show();
            }

            // 리스트만 열어보고 아이템을 선택하지 않은 경우
            @Override
             public void onNothingSelected(AdapterView<?> adapterView) {
            }

        });


        return view;
    }

 

 

3. textlines.xml (drawable 디렉토리)

 

<?xml version="1.0" encoding="utf-8"?>

<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:android="http://schemas.android.com/aapt">

    <item
        android:bottom="-2dp"
        android:left="-2dp"
        android:right="-2dp"
        android:top="1px">


          <shape android:shape="rectangle">
            <stroke
                android:width="1dp"
                android:color="#EAEAEA" />

               <solid android:color="#FFFFFF" />

         </shape>

 

    </item>

</layer-list>

 

 

4. spinner_item.xml (drawable 디렉토리)

 

<?xml version="1.0" encoding="utf-8"?>

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="14sp"
    android:padding="10dp"/>



        
    

반응형

댓글()

탭 스와이프 (tab swipe) 사용하기

프로그래밍/Android (Java)|2019. 4. 19. 14:49
반응형

https://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

 

잘되는것 확인 하였음.

반응형

댓글()

인트로 슬라이드 화면 구성하기

프로그래밍/Android (Java)|2019. 4. 19. 12:56
반응형

[출처] https://www.javatpoint.com/android-introduction-slider-example

소스는 잘 된다. 빌드를 하면 이미지가 두개 없다고 나오는데, 아무거나 가져다 놓고 빌드하면 화면을 볼수 있다.

 

activity_main.xml

 

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  

  4.     xmlns:tools="http://schemas.android.com/tools"  

  5.     android:layout_width="match_parent"  

  6.     android:layout_height="match_parent"  

  7.     android:background="@color/bg_mainactivity"  

  8.     tools:context="example.javatpoint.com.introonetimefirsttime.MainActivity">  

  9.   

  10.   

  11.     <TextView  

  12.         android:layout_width="wrap_content"  

  13.         android:layout_height="wrap_content"  

  14.         android:layout_marginEnd="8dp"  

  15.         android:layout_marginStart="8dp"  

  16.         android:layout_marginTop="176dp"  

  17.         android:textSize="18dp"  

  18.         android:text="This is your MainActivity or Home Page"  

  19.         android:textColor="@android:color/white"  

  20.         app:layout_constraintEnd_toEndOf="parent"  

  21.         app:layout_constraintHorizontal_bias="0.503"  

  22.         app:layout_constraintStart_toStartOf="parent"  

  23.         app:layout_constraintTop_toTopOf="parent" />  

  24.   

  25.     <Button  

  26.         android:id="@+id/btn_click"  

  27.         android:layout_width="wrap_content"  

  28.         android:layout_height="wrap_content"  

  29.         android:layout_marginBottom="96dp"  

  30.         android:layout_marginEnd="8dp"  

  31.         android:layout_marginStart="8dp"  

  32.         android:text="Button"  

  33.         android:onClick="btn_Click"  

  34.         app:layout_constraintBottom_toBottomOf="parent"  

  35.         app:layout_constraintEnd_toEndOf="parent"  

  36.         app:layout_constraintHorizontal_bias="0.501"  

  37.         app:layout_constraintStart_toStartOf="parent" />  

  38.   

  39. </android.support.constraint.ConstraintLayout>  


Create an activity_welcome.xml file and add the following code. It is used for the layout of slider.

activity_welcome.xml

 

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  

  4.     xmlns:tools="http://schemas.android.com/tools"  

  5.     android:layout_width="match_parent"  

  6.     android:layout_height="match_parent"  

  7.     tools:showIn="@layout/activity_welcome">  

  8.   

  9.   

  10.     <android.support.v4.view.ViewPager  

  11.         android:id="@+id/view_pager"  

  12.         android:layout_width="match_parent"  

  13.         android:layout_height="match_parent" />  

  14.   

  15.     <LinearLayout  

  16.         android:id="@+id/layoutDots"  

  17.         android:layout_width="match_parent"  

  18.         android:layout_height="@dimen/dots_height"  

  19.         android:layout_alignParentBottom="true"  

  20.         android:layout_marginBottom="@dimen/dots_margin_bottom"  

  21.         android:gravity="center"  

  22.         android:orientation="horizontal">  

  23.   

  24.     </LinearLayout>  

  25.   

  26.     <View  

  27.         android:layout_width="match_parent"  

  28.         android:layout_height="1dp"  

  29.         android:alpha=".5"  

  30.         android:layout_above="@id/layoutDots"  

  31.         android:background="@android:color/white" />  

  32.   

  33.     <Button  

  34.         android:id="@+id/btn_next"  

  35.         android:layout_width="wrap_content"  

  36.         android:layout_height="wrap_content"  

  37.         android:layout_alignParentBottom="true"  

  38.         android:layout_alignParentRight="true"  

  39.         android:background="@null"  

  40.         android:text="@string/next"  

  41.         android:textColor="@android:color/white" />  

  42.   

  43.     <Button  

  44.         android:id="@+id/btn_skip"  

  45.         android:layout_width="wrap_content"  

  46.         android:layout_height="wrap_content"  

  47.         android:layout_alignParentBottom="true"  

  48.         android:layout_alignParentLeft="true"  

  49.         android:background="@null"  

  50.         android:text="@string/skip"  

  51.         android:textColor="@android:color/white" />  

  52.   

  53. </RelativeLayout>  


Now create the layout for the welcome sliders as welcome_slide1.xml and welcome_slide2.xml in layout directory.

welcome_slide1.xml

 

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  3.     android:layout_width="match_parent"  

  4.     android:layout_height="match_parent"  

  5.     android:background="@color/bg_screen1">  

  6.   

  7.     <LinearLayout  

  8.         android:layout_width="wrap_content"  

  9.         android:layout_height="wrap_content"  

  10.         android:layout_centerInParent="true"  

  11.         android:gravity="center_horizontal"  

  12.         android:orientation="vertical">  

  13.   

  14.         <ImageView  

  15.             android:layout_width="@dimen/img_width_height"  

  16.             android:layout_height="@dimen/img_width_height"  

  17.             android:src="@drawable/jtp_logo" />  

  18.   

  19.         <TextView  

  20.             android:layout_width="wrap_content"  

  21.             android:layout_height="wrap_content"  

  22.             android:text="@string/slide_1_title"  

  23.             android:textColor="@android:color/white"  

  24.             android:textSize="@dimen/slide_title"  

  25.             android:textStyle="bold" />  

  26.   

  27.         <TextView  

  28.             android:layout_width="wrap_content"  

  29.             android:layout_height="wrap_content"  

  30.             android:layout_marginTop="20dp"  

  31.             android:paddingLeft="@dimen/desc_padding"  

  32.             android:paddingRight="@dimen/desc_padding"  

  33.             android:text="@string/slide_1_desc"  

  34.             android:textAlignment="center"  

  35.             android:textColor="@android:color/white"  

  36.             android:textSize="@dimen/slide_desc" />  

  37.   

  38.     </LinearLayout>  

  39. </RelativeLayout>  


welcome_slide2.xml

 

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  3.     android:layout_width="match_parent"  

  4.     android:layout_height="match_parent"  

  5.     android:background="@color/bg_screen2">  

  6.     <LinearLayout  

  7.         android:layout_width="wrap_content"  

  8.         android:layout_height="wrap_content"  

  9.         android:layout_centerInParent="true"  

  10.         android:gravity="center_horizontal"  

  11.         android:orientation="vertical">  

  12.   

  13.         <ImageView  

  14.             android:layout_width="@dimen/img_width_height"  

  15.             android:layout_height="@dimen/img_width_height"  

  16.             android:src="@drawable/image" />  

  17.   

  18.         <TextView  

  19.             android:layout_width="wrap_content"  

  20.             android:layout_height="wrap_content"  

  21.             android:text="@string/slide_2_title"  

  22.             android:textColor="@android:color/white"  

  23.             android:textSize="@dimen/slide_title"  

  24.             android:textStyle="bold" />  

  25.   

  26.         <TextView  

  27.             android:layout_width="wrap_content"  

  28.             android:layout_height="wrap_content"  

  29.             android:layout_marginTop="20dp"  

  30.             android:paddingLeft="@dimen/desc_padding"  

  31.             android:paddingRight="@dimen/desc_padding"  

  32.             android:text="@string/slide_2_desc"  

  33.             android:textAlignment="center"  

  34.             android:textColor="@android:color/white"  

  35.             android:textSize="@dimen/slide_desc" />  

  36.   

  37.     </LinearLayout>  

  38.   

  39. </RelativeLayout>  


colors.xml

 

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <resources>  

  3.     <color name="colorPrimary">#3F51B5</color>  

  4.     <color name="colorPrimaryDark">#303F9F</color>  

  5.     <color name="colorAccent">#FF4081</color>  

  6.     <color name="bg_mainactivity">#d4e6e3</color>  

  7.     <!-- Screens background color-->  

  8.     <color name="bg_screen1">#16c266</color>  

  9.     <color name="bg_screen2">#90c2bb</color>  

  10.   

  11.     <!-- dots inactive colors -->  

  12.     <color name="dot_dark_screen1">#39d1ba</color>  

  13.     <color name="dot_dark_screen2">#14a895</color>  

  14.   

  15.     <!-- dots active colors -->  

  16.     <color name="dot_light_screen1">#8de7f9</color>  

  17.     <color name="dot_light_screen2">#8cf9eb</color>  

  18.   

  19.    <array name="array_dot_active">  

  20.         <item>@color/dot_light_screen1</item>  

  21.         <item>@color/dot_light_screen2</item>  

  22.     </array>  

  23.   

  24.     <array name="array_dot_inactive">  

  25.         <item>@color/dot_dark_screen1</item>  

  26.         <item>@color/dot_dark_screen2</item>  

  27.     </array>  

  28. </resources>  


strings.xml

 

  1. <resources>  

  2.     <string name="app_name">IntroOneTimeFirstTime</string>  

  3.   

  4.     <string name="next">NEXT</string>  

  5.     <string name="skip">SKIP</string>  

  6.     <string name="start">GOT IT</string>  

  7.   

  8.     <string name="slide_1_title">Welcome to Javatpoint!</string>  

  9.     <string name="slide_1_desc">Javatpoint is passionate to offer better technical content to the world.</string>  

  10.   

  11.     <string name="slide_2_title">Android</string>  

  12.     <string name="slide_2_desc">Android is a mobile operating system developed by Google.</string>  

  13.   

  14. </resources>  


dimens.xml

 

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <resources>  

  3.     <!-- Default screen margins, per the Android Design guidelines. -->  

  4.     <dimen name="activity_horizontal_margin">16dp</dimen>  

  5.     <dimen name="activity_vertical_margin">16dp</dimen>  

  6.     <dimen name="fab_margin">16dp</dimen>  

  7.     <dimen name="dots_height">30dp</dimen>  

  8.     <dimen name="dots_margin_bottom">20dp</dimen>  

  9.     <dimen name="img_width_height">120dp</dimen>  

  10.     <dimen name="slide_title">30dp</dimen>  

  11.     <dimen name="slide_desc">16dp</dimen>  

  12.     <dimen name="desc_padding">40dp</dimen>  

  13.   

  14. </resources>  


Create a PrefManager.java class and add the following code. In the class, we use SharedPreferences class that keeps the preference name and a Boolean state true if the app is launched for the first time.

PrefManager.java

 

  1. package example.javatpoint.com.introonetimefirsttime;  

  2.   

  3. import android.content.Context;  

  4. import android.content.SharedPreferences;  

  5.   

  6. public class PrefManager {  

  7.     SharedPreferences pref;  

  8.     SharedPreferences.Editor editor;  

  9.     Context _context;  

  10.     // shared pref mode  

  11.     int PRIVATE_MODE = 0;  

  12.   

  13.     // Shared preferences file name  

  14.     private static final String PREF_NAME = "welcome";  

  15.     private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";  

  16.   

  17.     public PrefManager(Context context) {  

  18.         this._context = context;  

  19.         pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);  

  20.         editor = pref.edit();  

  21.     }  

  22.   

  23.     public void setFirstTimeLaunch(boolean isFirstTime) {  

  24.         editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);  

  25.         editor.commit();  

  26.     }  

  27.   

  28.     public boolean isFirstTimeLaunch() {  

  29.         return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);  

  30.     }  

  31. }  


In the WelcomeActivity.java class file, add the following code.

In this class, we are performing the following tasks:

  • Checking the first time launch of the application using prefManager.isFirstTimeLaunch() method, if it returns true then the file MainActivity.java will be launched.

  • Adding the slider with Skip and Next buttons.

WelcomeActivity.java

 

  1. package example.javatpoint.com.introonetimefirsttime;  

  2.   

  3. import android.support.v4.view.ViewPager;  

  4. import android.support.v7.app.AppCompatActivity;  

  5. import android.os.Bundle;  

  6. import android.content.Context;  

  7. import android.content.Intent;  

  8. import android.graphics.Color;  

  9. import android.os.Build;  

  10. import android.support.v4.view.PagerAdapter;  

  11. import android.text.Html;  

  12. import android.view.LayoutInflater;  

  13. import android.view.View;  

  14. import android.view.ViewGroup;  

  15. import android.view.Window;  

  16. import android.view.WindowManager;  

  17. import android.widget.Button;  

  18. import android.widget.LinearLayout;  

  19. import android.widget.TextView;  

  20. public class WelcomeActivity extends AppCompatActivity {  

  21.   

  22.     private ViewPager viewPager;  

  23.     private MyViewPagerAdapter myViewPagerAdapter;  

  24.     private LinearLayout dotsLayout;  

  25.     private TextView[] dots;  

  26.     private int[] layouts;  

  27.     private Button btnSkip, btnNext;  

  28.     private PrefManager prefManager;  

  29.   

  30.     @Override  

  31.     protected void onCreate(Bundle savedInstanceState) {  

  32.         super.onCreate(savedInstanceState);  

  33.   

  34.         // Checking for first time launch - before calling setContentView()  

  35.         prefManager = new PrefManager(this);  

  36.         if (!prefManager.isFirstTimeLaunch()) {  

  37.             launchHomeScreen();  

  38.             finish();  

  39.         }  

  40.   

  41.         // Making notification bar transparent  

  42.         if (Build.VERSION.SDK_INT >= 21) {  

  43.             getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);  

  44.         }  

  45.   

  46.         setContentView(R.layout.activity_welcome);  

  47.   

  48.         viewPager = (ViewPager) findViewById(R.id.view_pager);  

  49.         dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);  

  50.         btnSkip = (Button) findViewById(R.id.btn_skip);  

  51.         btnNext = (Button) findViewById(R.id.btn_next);  

  52.   

  53.   

  54.         // layouts of welcome sliders  

  55.         layouts = new int[]{  

  56.                 R.layout.welcome_slide1,  

  57.                 R.layout.welcome_slide2  

  58.         };  

  59.   

  60.         // adding bottom dots  

  61.         addBottomDots(0);  

  62.   

  63.         // making notification bar transparent  

  64.         changeStatusBarColor();  

  65.   

  66.         myViewPagerAdapter = new MyViewPagerAdapter();  

  67.         viewPager.setAdapter(myViewPagerAdapter);  

  68.         viewPager.addOnPageChangeListener(viewPagerPageChangeListener);  

  69.   

  70.         btnSkip.setOnClickListener(new View.OnClickListener() {  

  71.             @Override  

  72.             public void onClick(View v) {  

  73.                 launchHomeScreen();  

  74.             }  

  75.         });  

  76.   

  77.         btnNext.setOnClickListener(new View.OnClickListener() {  

  78.             @Override  

  79.             public void onClick(View v) {  

  80.                 // checking for last page if true launch MainActivity  

  81.                 int current = getItem(+1);  

  82.                 if (current < layouts.length) {  

  83.                     // move to next screen  

  84.                     viewPager.setCurrentItem(current);  

  85.                 } else {  

  86.                     launchHomeScreen();  

  87.                 }  

  88.             }  

  89.         });  

  90.     }  

  91.   

  92.     private void addBottomDots(int currentPage) {  

  93.         dots = new TextView[layouts.length];  

  94.   

  95.         int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);  

  96.         int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);  

  97.   

  98.         dotsLayout.removeAllViews();  

  99.         for (int i = 0; i < dots.length; i++) {  

  100.             dots[i] = new TextView(this);  

  101.             dots[i].setText(Html.fromHtml("?"));  

  102.             dots[i].setTextSize(35);  

  103.             dots[i].setTextColor(colorsInactive[currentPage]);  

  104.             dotsLayout.addView(dots[i]);  

  105.         }  

  106.   

  107.         if (dots.length > 0)  

  108.             dots[currentPage].setTextColor(colorsActive[currentPage]);  

  109.     }  

  110.   

  111.     private int getItem(int i) {  

  112.         return viewPager.getCurrentItem() + i;  

  113.     }  

  114.   

  115.     private void launchHomeScreen() {  

  116.         prefManager.setFirstTimeLaunch(false);  

  117.         startActivity(new Intent(WelcomeActivity.this, MainActivity.class));  

  118.         finish();  

  119.     }  

  120.   

  121.     //  viewpager change listener  

  122.     ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {  

  123.   

  124.         @Override  

  125.         public void onPageSelected(int position) {  

  126.             addBottomDots(position);  

  127.   

  128.             // changing the next button text 'NEXT' / 'GOT IT'  

  129.             if (position == layouts.length - 1) {  

  130.                 // last page. make button text to GOT IT  

  131.                 btnNext.setText(getString(R.string.start));  

  132.                 btnSkip.setVisibility(View.GONE);  

  133.             } else {  

  134.                 // still pages are left  

  135.                 btnNext.setText(getString(R.string.next));  

  136.                 btnSkip.setVisibility(View.VISIBLE);  

  137.             }  

  138.         }  

  139.   

  140.         @Override  

  141.         public void onPageScrolled(int arg0, float arg1, int arg2) {  

  142.   

  143.         }  

  144.   

  145.         @Override  

  146.         public void onPageScrollStateChanged(int arg0) {  

  147.   

  148.         }  

  149.     };  

  150.   

  151.     // Making notification bar transparent  

  152.        

  153.     private void changeStatusBarColor() {  

  154.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {  

  155.             Window window = getWindow();  

  156.             window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  

  157.             window.setStatusBarColor(Color.TRANSPARENT);  

  158.         }  

  159.     }  

  160.   

  161.     /** 

  162.      * View pager adapter 

  163.      */  

  164.     public class MyViewPagerAdapter extends PagerAdapter {  

  165.         private LayoutInflater layoutInflater;  

  166.   

  167.         public MyViewPagerAdapter() {  

  168.         }  

  169.   

  170.         @Override  

  171.         public Object instantiateItem(ViewGroup container, int position) {  

  172.             layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);  

  173.   

  174.             View view = layoutInflater.inflate(layouts[position], container, false);  

  175.             container.addView(view);  

  176.   

  177.             return view;  

  178.         }  

  179.   

  180.         @Override  

  181.         public int getCount() {  

  182.             return layouts.length;  

  183.         }  

  184.   

  185.         @Override  

  186.         public boolean isViewFromObject(View view, Object obj) {  

  187.             return view == obj;  

  188.         }  

  189.   

  190.   

  191.         @Override  

  192.         public void destroyItem(ViewGroup container, int position, Object object) {  

  193.             View view = (View) object;  

  194.             container.removeView(view);  

  195.         }  

  196.     }  

  197. }  


In the MainActivity.java class, add the following code. This class checks the state returned by the SharedPreferences.

MainActivity.java

 

  1. package example.javatpoint.com.introonetimefirsttime;  

  2.   

  3. import android.content.Intent;  

  4. import android.support.v7.app.AppCompatActivity;  

  5. import android.os.Bundle;  

  6. import android.view.View;  

  7. import android.widget.Toast;  

  8.   

  9. public class MainActivity extends AppCompatActivity {  

  10.   

  11.     @Override  

  12.     protected void onCreate(Bundle savedInstanceState) {  

  13.         super.onCreate(savedInstanceState);  

  14.         setContentView(R.layout.activity_main);  

  15.         PrefManager prefManager = new PrefManager(getApplicationContext());  

  16.         if(prefManager.isFirstTimeLaunch()){  

  17.             prefManager.setFirstTimeLaunch(false);  

  18.             startActivity(new Intent(MainActivity.this, WelcomeActivity.class));  

  19.             finish();  

  20.         }  

  21.     }  

  22.     protected void btn_Click(View view){  

  23.         Toast.makeText(MainActivity.this"clicked on button", Toast.LENGTH_LONG).show();  

  24.     }  

  25. }  


AndroidMenifest.java

 

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  

  3.     package="example.javatpoint.com.introonetimefirsttime">  

  4.   

  5.     <application  

  6.         android:allowBackup="true"  

  7.         android:icon="@mipmap/ic_launcher"  

  8.         android:label="@string/app_name"  

  9.         android:roundIcon="@mipmap/ic_launcher_round"  

  10.         android:supportsRtl="true"  

  11.         android:theme="@style/AppTheme">  

  12.   

  13.         <activity android:name=".WelcomeActivity">  

  14.             <intent-filter>  

  15.                 <action android:name="android.intent.action.MAIN" />  

  16.   

  17.                 <category android:name="android.intent.category.LAUNCHER" />  

  18.             </intent-filter>  

  19.         </activity>  

  20.         <activity  

  21.             android:name=".MainActivity"/>  

  22.     </application>  

  23.   

  24. </manifest>  

Output:

 

 

 

 

 

[출처] https://www.javatpoint.com/android-introduction-slider-example

반응형

댓글()

FCM 사용하기 (2019-04-17) - 새버전

프로그래밍/Android (Java)|2019. 4. 17. 16:02
반응형

앱을 구동하면 toast 로 token 값을 확인할 수 있다.

서버랑 연동하기 위해 내용을 보강해야 함.

===============================

 

안드로이드 FCM 관련 글입니다.

 

구글에서는 예전부터 지속적으로 GCM이 아닌 FCM사용을 권고하였습니다. 

 

그리고 안드로이드 신규 버전인 9.0파이버전부터는 GCM이 정상적인 작동을 하지 않습니다.

(관련 링크)

 

FCM프로젝트를 생성 및 푸시 테스트까지 진행해 보도록 하겠습니다.

 

FCM관련 콘솔 홈페이지로 접속합니다(링크)

 

구글계정이 로그인 되어있는 상태에서 위의 링크를 클릭하면 아래와 같은 화면으로 진입합니다.

 

화면에서 프로젝트 추가를 클릭합니다.

 

 

 

다음부터는 스크린샷을 따라서 해주시면 되겠습니다.

 

 

 

 

 

 

 

아래 디버그 서명 인증서는 선택사항이며 꼭 하지 않으셔도 됩니다.

 

하지만 밑줄친 기능을 사용하실려면 등록하시면 됩니다.

 

 

 

 

 

 

위의 스크린샷에서 처럼 google-service.json 파일을 다운받은 뒤 현재 FCM사용을 위해 

 

생성한 프로젝트 app폴더 안에 파일을 넣도록 합니다.

 

 

 

 

여기까지 하셨으면 기본적으로 FCM을 준비하는건 다되셨습니다.

 

이제 프로젝트 내부에 Gradle 셋팅과 FCM 구현이 남아있는데요.

 

먼저 Gradle 셋팅입니다.

 

프로젝트 내 dependencies 안에 아래 코드를 넣어줍니다.

 

implementation 'com.google.firebase:firebase-messaging:17.3.4'

implementation 'com.google.firebase:firebase-core:16.0.4'

 

 

dependencies 밖에 json파일 관련 아래 코드를 넣어줍니다.

 

apply plugin: 'com.google.gms.google-services'

 

 

두번째 앱 내의 denpendencies 안에 아래 코드를 넣어줍니다.

 

classpath 'com.android.tools.build:gradle:3.2.1'

classpath 'com.google.gms:google-services:4.0.1'

 

 

Gradle 스크린샷 입니다.

 

 

 

 

 

 

여기까지 준비가 되셨다면 이제 FCM을 구현해주면 됩니다.

 

프로젝트내에 FirebaseInstanceIDService 라는 클래스 파일을 생성한 뒤 아래와 같이 구현합니다. 

 

메소드에 대한 설명은 주석으로 되어있습니다.

 

package kr.com.fcmtarget.fcm;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.NotificationCompat;

// Androidx 에서는 위에 대신에 아래것을 사용한다.

//import androidx.core.app.NotificationCompat;

 

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import kr.com.fcmtarget.R;


public class FirebaseInstanceIDService extends FirebaseMessagingService {

    /**
     * 구글 토큰을 얻는 값입니다.
     * 아래 토큰은 앱이 설치된 디바이스에 대한 고유값으로 푸시를 보낼때 사용됩니다.
     * **/

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("Firebase", "FirebaseInstanceIDService : " + s);
    }

    /**
     * 메세지를 받았을 경우 그 메세지에 대하여 구현하는 부분입니다.
     * **/
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        if (remoteMessage != null && remoteMessage.getData().size() > 0) {
            sendNotification(remoteMessage);
        }
    }


    /**
     * remoteMessage 메세지 안애 getData와 getNotification이 있습니다.
     * 이부분은 차후 테스트 날릴때 설명 드리겠습니다.
     * **/
    private void sendNotification(RemoteMessage remoteMessage) {

        String title = remoteMessage.getData().get("title");
        String message = remoteMessage.getData().get("message");

        /**
         * 오레오 버전부터는 Notification Channel이 없으면 푸시가 생성되지 않는 현상이 있습니다.
         * **/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            String channel = "채널";
            String channel_nm = "채널명";

            NotificationManager notichannel = (android.app.NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channelMessage = new NotificationChannel(channel, channel_nm,
                    android.app.NotificationManager.IMPORTANCE_DEFAULT);
            channelMessage.setDescription("채널에 대한 설명.");
            channelMessage.enableLights(true);
            channelMessage.enableVibration(true);
            channelMessage.setShowBadge(false);
            channelMessage.setVibrationPattern(new long[]{100, 200, 100, 200});
            notichannel.createNotificationChannel(channelMessage);

            NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(this, channel)
                            .setSmallIcon(R.drawable.ic_launcher_background)
                            .setContentTitle(title)
                            .setContentText(message)
                            .setChannelId(channel)
                            .setAutoCancel(true)
                            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(9999, notificationBuilder.build());

        } else {
            NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(this, "")
                            .setSmallIcon(R.drawable.ic_launcher_background)
                            .setContentTitle(title)
                            .setContentText(message)
                            .setAutoCancel(true)
                            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(9999, notificationBuilder.build());

        }
    }
}

 

위의 소스를 완성 하셨다면AndroidManifest.xml에 아래 소스까지 해주시면 완성입니다.

 

 

 

<service android:name=".FirebaseInstanceIDService" android:stopWithTask="false">

<intent-filter>

<action android:name="com.google.firebase.MESSAGING_EVENT" />

<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>

</intent-filter>

</service>

 

 

===== MainActivity.java 내용 추가 =====

 

 

 

public class MainActivity extends AppCompatActivity {

 

private static final String TAG = MainActivity.class.getSimpleName();

 

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


        // FCM
        Task id = FirebaseInstanceId.getInstance().getInstanceId();
        id.addOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {
                if (task.isSuccessful()) {
                    InstanceIdResult result = task.getResult();
                    String id = result.getId();
                    String token = result.getToken();

                    Log.d(TAG, "Token id : " + id);
                    Log.d(TAG, "Token : " + token);

                    String aaa = task.getResult().getToken();
                    Toast.makeText (getBaseContext(), aaa, Toast.LENGTH_SHORT).show();

                } else {
                    Log.d(TAG, "Token Exception : " + task.getException().toString());
                }

            }
        });

 

    }

}

 

==================

 

 

 

자 이제 테스트를 해봐야겠죠?

 

데이터를 보내는 페이로드 관련 및 테스트는 다음글에 적도록 하겠습니다.



출처: https://kwon8999.tistory.com/entry/안드로이드-FCM-구현1프로젝트-셋팅-및-구현 [Kwon's developer]

 

 

 

반응형

댓글()

변수에 숫자만 있는지 확인

프로그래밍/BASH SHELL|2019. 4. 5. 09:46
반응형

# vi no.sh

#!/bin/bash
v=$1
if [ $v -eq $v 2> /dev/null ]; then
   echo $v is a number
else
   echo $v isnt a number
fi

 

사용법

# sh no.sh 123

반응형

댓글()

쉘스크립트 include 하기

프로그래밍/BASH SHELL|2019. 4. 5. 08:46
반응형

php 의 include 함수와 같이 쉘스크립트에서 외부의 파일을 가져와 적용하기 위해서는 아래와 같은 코드로 작성한다.

 

. ./other.sh

 

 

반응형

댓글()