WebView를 스크롤하면 툴바 숨기기

 

CoordinatorLayout 과 NestedScrollView 사용

 

 

build.gradle (:app)

1
2
3
    implementation 'androidx.appcompat:appcompat:1.1.0'
 
 

- Material Design 라이브러리를 추가

 

 

styles.xml

1
2
3
4
5
6
7
8
9
10
11
12
<resources>
 
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
 
</resources>
 
 

- 툴바를 레이아웃 xml에 추가할 것이므로 styles에서는 액션바가 없는 스타일을 상속한다

 

 

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?xml version="1.0" encoding="utf-8"?>
<!--
CoordinatorLayout : 부모뷰-자식뷰 , 자식뷰들간의 여러 인터렉션을 지원하는 컨테이너
NestedScrollView : 한 화면에 여러개의 스크롤 사용
 
fitsSystemWindows : status bar와 ui가 안겹치도록 조정 (뷰가 상태바와 소프트키 영역을 제외한 영역까지만 차지한다)
-->
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">
 
 
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 
        <!--
        layout_scrollFlags : AppBarLayout 및 하위의 스크롤 동작 담당
            scroll :  내용과 같이 스크롤, 툴바를 다시 볼려면 스크롤을 위로 끝까지 올려야함
            enterAlways : 맨위에 없어도 위로 스크롤시 바로 툴바가 보임
            enterAlwaysCollapsed : enterAlways와 동작이 비슷하지만 스크롤을 위로 끝까지 올려야 전체뷰가 보임 (스크롤하면 툴바도 같이 스크롤되어 안보임)
            exitUntilCollapsed : 아래/위로 스크롤시 축소된 툴바가 보이고 스크롤을 위로 끝까지 올려야 전체뷰가 보임 (스크롤해도 축소된 툴바가 보임)
            snap : 툴바가 위쪽에서 얼마나 떨어져 있는지에 따라 숨겨지거나 보여짐
         -->
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:contentInsetStart="0dp"
            app:contentInsetEnd="0dp"
            app:contentInsetLeft="0dp"
            app:contentInsetRight="0dp"
            app:contentInsetStartWithNavigation="0dp">
 
            <LinearLayout
                android:paddingLeft="8dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <TextView
                    android:text="툴바"
                    android:textSize="16dp"
                    android:textColor="#ffffff"
                    android:layout_gravity="center_vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </LinearLayout>
 
 
 
 
    <!-- layout_behavior : 자식뷰의 변화 상태를 부모뷰/다른 자식뷰한테 전달 (여기서는 스크롤했을 경우 다른 자식뷰에게 전달한다) -->
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
 
            <WebView
                android:id="@+id/webView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
 
        </LinearLayout>
 
 
 
 
 

- 아래로 스크롤하면 툴바가 사라졌다가 위로 스크롤하면 툴바가 나타난다

 

 

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 
 
public class MainActivity extends AppCompatActivity {
 
    // ui
    WebView webView;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        webView = (WebView)findViewById( R.id.webView );
        webView.setNetworkAvailable( true );
 
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled( true );
 
        webView.setWebChromeClient( new WebChromeClient() );
        webView.setWebViewClient( new WebViewClient() );
 
        webView.loadUrl( "https://www.naver.com");
    }
}
 
 

- 테스트를 위해 웹뷰에 네이버를 띄운다

 

 

결과

처음에는 툴바가 보였다가 아래로 스크롤하면 툴바가 사라졌다가 위로 조금만 스크롤해도 툴바가 다시 보인다

Glide 라이브러리로 gif이미지 로딩 

 

github : https://github.com/bumptech/glide

 

 

build.gradle (:app)

1
2
3
4
5
    // Glide
    // annotationProcessor : annotation processor classpath 에서 compile processor classpath를 분리하여 빌드 성능개선
    annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
 
  • glide 라이브러리 추가

 

 

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
 
 
public class MainActivity extends AppCompatActivity {
 
    ImageView imgGif;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        imgGif = (ImageView)findViewById( R.id.img_gif );
 
        Glide.with( this )
                .asGif()    // GIF 로딩
                .load( R.raw.loading )
                .diskCacheStrategy( DiskCacheStrategy.RESOURCE )    // Glide에서 캐싱한 리소스와 로드할 리소스가 같을때 캐싱된 리소스 사용
                .into( imgGif );
    }
}
 
 
  • GIF 이미지를 raw 폴더에 넣음

 

그외 glide 라이브러리 함수

  • override() : 지정한 크기로 이미지 사이즈 설정

  • placeholder() : 이미지가 로딩할 동안 보여줄 기본 이미지

  • error() : 이미지 로딩 실패시 보여줄 에러 이미지

 

 

activity_main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">
 
    <ImageView
        android:id="@+id/img_gif"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
</RelativeLayout>
 
 

 

 

결과

Retrofit2 예제

안전한 타입의 HTTP Client 라이브러리로 Android 및 Java 애플리케이션에서 사용합니다

최소요구사항 : Java 8+ or Android API 21+

 

github : https://github.com/square/retrofit

 

 

build.gradle (:app)

1
2
3
4
    // retrofit2
    implementation group: 'com.squareup.retrofit2', name: 'retrofit', version: '2.8.1'
    implementation group: 'com.squareup.retrofit2', name: 'converter-gson', version: '2.8.1' // JSON을 직렬화
    implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.6' // 직렬화된 JSON을 객체로 역직렬화
  • Retrofit2 라이브러리 추가

 

 

AndroidManifest.xml

1
<uses-permission android:name="android.permission.INTERNET" />
  • 인터넷 사용 권한 추가

 

 

ApiInterface.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
public interface ApiInterface {
 
    // base_url + "api/login" 으로 POST 통신
    @POST("api/login")
    Call<ResLoginData> requestPostLogin(@Body ReqLoginData reqLoginData );   // @Body : request 파라미터
 
    // base_url + "api/users" 으로 GET 통신
    @GET("api/users")
    Call<ResUsersData> requestGetUsersDetail( @Query(value = "page", encoded = trueString page );   // @Query : url에 쿼리 파라미터 추가, encoded - true
 
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
  • HTTP 통신 인터페이스

 

 

HttpClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import retrofit2.Retrofit;
 
public class HttpClient {
 
    private static Retrofit retrofit;
 
    // Http 통신을 위한 Retrofit 객체반환
    public static Retrofit getRetrofit() {
        if( retrofit == null )
        {
            Retrofit.Builder builder = new Retrofit.Builder();
            builder.baseUrl( "https://reqres.in/" );
            builder.addConverterFactory( GsonConverterFactory.create() );  // 받아오는 Json 구조의 데이터를 객체 형태로 변환
 
            retrofit = builder.build();
        }
 
        return retrofit;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
  • Retrofit 객체를 생성

 

 

ReqLoginData.java

1
2
3
4
5
6
7
8
9
10
11
// api/login 요청 데이터
public class ReqLoginData {
 
    String email;
    String password;
 
    public ReqLoginData( String email, String password ) {
        this.email = email;
        this.password = password;
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
  • api/login 통신의 요청 객체

 

 

ResLoginData.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
import androidx.annotation.NonNull;
 
// api/login 응답 데이터
public class ResLoginData {
 
    @Expose
    String token;
 
    @NonNull
    @Override
    public String toString() {
        return "[ResLoginData] token=" + token;
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
  • api/login 통신의 응답 객체

  • api/login 통신 결과값을 ResLoginData 객체에 맵핑한다

 

 

ResUsersData.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
 
 
import androidx.annotation.NonNull;
 
// api/users 응답 데이터
public class ResUsersData {
 
    @Expose
    int page;
    @Expose
    @SerializedName("per_page")
    int perPage;
    @Expose
    int total;
    @Expose
    @SerializedName("total_pages")
    int totalPages;
    @Expose
    List<Data> data;
    @Expose
    Ad ad;
 
 
    public class Data {
        int id;
        String email;
        @SerializedName("first_name")
        String firstName;
        @SerializedName("last_name")
        String lastName;
        String avatar;
 
        @NonNull
        @Override
        public String toString() {
            return "{id=" + id + " , email=" + email + " , firstName=" + firstName + " , lastName=" + lastName + " , avatar}";
        }
    }
 
    public class Ad {
        String company;
        String url;
        String text;
 
        @NonNull
        @Override
        public String toString() {
            return "{company=" + company + " , url=" + url + " , text=" + text + "}";
        }
    }
 
    @Override
    public String toString() {
        String str = "[ResUsersData] page=" + page + " , perPage=" + perPage + " , total=" + total + " , totalPages=" + totalPages + " , data= [";
        forint i=0; i<data.size(); i++ ) {
            str += data.get(i).toString();
            if( i < data.size()-1 ) {
                str += ",";
            }
        }
        str += "]";
        str += " , ad=" + ad.toString();
 
        return str;
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
  • api/users 통신의 응답 객체

  • api/users 통신 결과값을 ResUsersData 객체에 맵핑한다

 

 

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
 
import retrofit2.Callback;
import retrofit2.Response;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    private static String TAG = "MainActivity";
 
    ApiInterface api;
 
    // ui
    Button btnGet;
    Button btnPost;
    TextView txtResult;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
 
        btnGet = (Button)findViewById( R.id.btnGet );
        btnGet.setOnClickListener( this );
        btnPost = (Button)findViewById( R.id.btnPost );
        btnPost.setOnClickListener( this );
        txtResult = (TextView)findViewById( R.id.txtResult );
 
        api = HttpClient.getRetrofit().create( ApiInterface.class );
    }
 
    @Override
    public void onClick(View view) {
        switch ( view.getId() ) {
            case R.id.btnPost:
                txtResult.setText("");
                requestPost();
                break;
 
            case R.id.btnGet:
                txtResult.setText("");
                requestGet();
                break;
        }
    }
 
    // POST 통신요청
    public void requestPost() {
        ReqLoginData reqLoginData = new ReqLoginData( "eve.holt@reqres.in" , "cityslicka" );
        Call<ResLoginData> call = api.requestPostLogin( reqLoginData );
 
        // 비동기로 백그라운드 쓰레드로 동작
        call.enqueue( new Callback<ResLoginData>() {
            // 통신성공 후 텍스트뷰에 결과값 출력
            @Override
            public void onResponse(Call<ResLoginData> call, Response<ResLoginData> response) {
                txtResult.setText( response.body().toString() );    // body() - API 결과값을 객체에 맵핑
            }
 
            @Override
            public void onFailure(Call<ResLoginData> call, Throwable t) {
                txtResult.setText( "onFailure" );
            }
        } );
    }
 
    // GET 통신요청
    public void requestGet() {
        Call<ResUsersData> call = api.requestGetUsersDetail( "2" );
 
        // 비동기로 백그라운드 쓰레드로 동작
        call.enqueue(new Callback<ResUsersData>() {
            // 통신성공 후 텍스트뷰에 결과값 출력
            @Override
            public void onResponse(Call<ResUsersData> call, Response<ResUsersData> response) {
                txtResult.setText( response.body().toString() );
            }
 
            // 통신실패
            @Override
            public void onFailure(Call<ResUsersData> call, Throwable t) {
                txtResult.setText( "onFailure" );
            }
        });
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
  • POST통신과 GET통신 결과값을 TextView에 출력

 

 

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 
        <Button
            android:id="@+id/btnPost"
            android:text="POST"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
 
        <Button
            android:id="@+id/btnGet"
            android:text="GET"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
 
    </LinearLayout>
 
    <TextView
        android:id="@+id/txtResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
 
</LinearLayout>
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

 

 

결과

GCM 구현2 - 서버

 

 

안드로이드 : http://ghj1001020.tistory.com/783?category=719597

서버 : http://ghj1001020.tistory.com/784?category=756570

 

 

가이드 : https://developers.google.com/cloud-messaging/http

 

1. 앱은 GCM 토큰을 가져와서 앱에 저장합니다

2. 서버에서 앱에 저장된 GCM 토큰을 사용하여 메시지를 요청합니다

3. 앱이 GCM 메시지 수신하고 알림을 띄웁니다

* 테스트 용도 이므로 토큰을 서버에 저장하는 부분은 제외했습니다. (서버에서는 디바이스의 GCM 토큰을 하드코딩해서 보냅니다)

 

 

1. gcm-server 라이브러리 이용

 

pom.xml

1
2
3
4
5
6
7
        <!-- GCM -->
        <!-- https://mvnrepository.com/artifact/com.google.gcm/gcm-server -->
        <dependency>
            <groupId>com.google.gcm</groupId>
            <artifactId>gcm-server</artifactId>
            <version>1.0.0</version>
        </dependency>
cs

* 라이브러리 jar 파일을 받아서 사용하실때는 json-simple 라이브러리도 필요합니다

* https://github.com/google/gcm/tree/master/client-libraries/java/rest-client/src/com/google/android/gcm/server

 

 

GcmSender.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    //GCM Url
    private final String GCM_URL = "https://gcm-http.googleapis.com/gcm/send";
 
    ...
 
    //GCM 전송 - 라이브러리 사용
    public void gcmSend(Map<StringString> datas) {
        Message.Builder builder = new Message.Builder();
        builder.delayWhileIdle(true);    //기기가 절전 상태에서도 수신될지 여부
        builder.timeToLive(60*1000);    //기기가 비활성화 상태일때 메시지 유효시간 (초)
        builder.collapseKey(UUID.randomUUID().toString());    //중복메시지도 전송될 수 있도록 고유키 생성
        //데이터 추가
        builder.addData( "title", datas.get("title") );
        builder.addData( "body", datas.get("body") );
 
        //메시지 생성
        Message message = builder.build();
        
        //단말 토큰 리스트 
        ArrayList<String> registIdList = new ArrayList<>();
        registIdList.add(REG_ID);
                
        try {
            Sender sender = new Sender(SERVER_KEY);
            MulticastResult multiResult = sender.send(message, registIdList, 1);    //retry 1회
            List<Result> resultList = multiResult.getResults();
            //결과출력 
            for( Result result : resultList ) {
                if( result.getMessageId() != null ) {
                    //성공
                    System.out.println("Success");
                }
                else {
                    //실패
                    System.out.println("Fail : "+result.getErrorCodeName());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
cs

* SERVER_KEY(서버키) 와 REG_ID(토큰) 는 각자 테스트 하시는 걸로 사용합니다

 

 

2. HttpsURLConnection 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    //GCM 전송 - HttpsUrlConnection 사용
    public void gcmSendUrl(Map<StringString> datas) {
        try {
            URL url = new URL(GCM_URL);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestProperty("Authorization""key="+SERVER_KEY);
            conn.setRequestProperty("Content-Type""application/json; UTF-8");
            
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            JSONObject jsonMsg = new JSONObject();
            jsonMsg.put( "title", datas.get("title") );
            jsonMsg.put( "body", datas.get("body") );
            
            JSONObject json = new JSONObject();
            json.put("to", REG_ID);
            json.put("delay_while_idle"true);
            json.put("data", jsonMsg);
 
            System.out.println("Param : "+json.toString());
            
            conn.setRequestProperty("Content-Length"String.valueOf(json.toString().length()));
            
            //보내기
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            osw.write(json.toString());
            osw.flush();
            osw.close();
 
            //받기
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
             
            StringBuffer strBuf = new StringBuffer();
            String inputLine;
            while((inputLine = in.readLine()) != null) { // response 출력
                strBuf.append(inputLine);
            }
            
            in.close();
            conn.disconnect();    
            
            //결과
            if(!strBuf.toString().isEmpty()) {
                System.out.println("Result : "+strBuf.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
cs

 

 

main

1
2
3
4
5
6
7
8
9
10
    public static void main(String[] args) {
        GcmSender gcmSender=  new GcmSender();
        //데이터
        Map<StringString> datas = new HashMap<>();
        datas.put("title""GCM 테스트");
        datas.put("body""GCM 테스트 중입니다.");
        
        gcmSender.gcmSend(datas);
//        gcmSender.gcmSendUrl(datas);
    }
cs

* title과 body 처럼 어떤 키-값으로 보낼지는 클라이언트와 미리 약속이 되어 있어야 합니다

 

 

결과

* 서버에서 전송한 GCM 메시지를 안드로이드에서 수신하여 알림으로 띄웠습니다

GCM 구현1 - Android

 

 

안드로이드 : http://ghj1001020.tistory.com/783?category=719597

서버 : http://ghj1001020.tistory.com/784?category=756570

 

 

가이드 : https://developers.google.com/cloud-messaging/android/client

 

1. 앱은 GCM 토큰을 가져와서 앱에 저장합니다

2. 서버에서 앱에 저장된 GCM 토큰을 사용하여 메시지를 요청합니다

3. 앱이 GCM 메시지 수신하고 알림을 띄웁니다

* 테스트 용도 이므로 토큰을 서버에 저장하는 부분은 제외했습니다. (서버에서는 디바이스의 GCM 토큰을 하드코딩해서 보냅니다)

 

 

build.gradle
1
2
3
4
5
dependencies {
    ...
    //gcm
    implementation 'com.google.android.gms:play-services-gcm:11.8.0'
}
cs

 

 

AndroidManifest.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    
 
    <application>
 
        ...
        <!-- GCM -->
        <!-- GCM으로 부터 message를 받을 수 있도록 권한선언 -->
        <receiver android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
 
                <category android:name="com.ghj.gcmex" />
            </intent-filter>
        </receiver>
 
        <!-- 등록 토큰 생성 및 업데이트 처리 -->
        <service android:name=".gcm.MyInstanceIDService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>
 
        <!-- 메시지 수신처리 -->
        <service android:name=".gcm.MyGcmListenerService"
android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            </intent-filter>
        </service>
 
        <!-- 토큰 가져오기 -->
        <service android:name=".gcm.RegistrationIntentService"
            android:exported="false" />
 
    </application>

cs

* 메시지 수신할 때 절전모드를 유지하기위해 WAKE_LOCK 권한을 줍니다

* com.google.android.gms.gcm.GcmReceiver 은 GCM으로부터 메시지를 받는 리시버입니다

 

 

MyInstanceIDService.java

1
2
3
4
5
6
7
8
9
10
public class MyInstanceIDService extends InstanceIDListenerService {
 
 
    //등록 토큰이 업데이트 되면 호출된다
    @Override
    public void onTokenRefresh() {
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
}
cs

* GCM 토큰이 업데이트 되면 호출되는 서비스 입니다

* 토큰을 가져와서 앱에 저장하기 위해 RegistrationIntentService 서비스를 호출합니다

 

 

RegistrationIntentService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//IntentService : 작업을 수행하는 스레드를 별도로 생성 , stopService도 자동적으로 호출
public class RegistrationIntentService extends IntentService {
 
    private static final String TAG = "RegistIntentService";
 
    public RegistrationIntentService()
    {
        super( TAG );
    }
 
 
    //서비스 시작시 호출
    @Override
    protected void onHandleIntent(@Nullable Intent intent)
    {
        String senderId = getString(R.string.gcm_sender_id);
 
        try {
            synchronized ( TAG ) {
                //토큰 가져와서 앱에 저장
                InstanceID instanceID = InstanceID.getInstance(this);
                String token = instanceID.getToken( senderId , GoogleCloudMessaging.INSTANCE_ID_SCOPE , null);
 
                Log.d("GCM_Token" , token);
                saveGcmToken(token);
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }
 
    //shared preferences 에 토큰 저장
    public void saveGcmToken(String token) {
        SharedPreferences pref = getSharedPreferences(getString(R.string.pref_gcm_token) , Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(getString(R.string.pref_key_gcm_token) , token);
        editor.commit();
    }
}
cs

* GCM 토큰을 가져와서 앱에 저장하는 서비스 입니다

 

 

MyGcmListenerService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
public class MyGcmListenerService extends GcmListenerService {
 
    private final String TAG = "MyGcmListenerService";
 
    //알림
    private final String GCM_DATA_KEY_TITLE = "title";
    private final String GCM_DATA_KEY_BODY = "body";
    private static int NOTIFICATION_ID = 0;
    private final long[] ALARM_PATTERN = new long[]{ 100100100100 };
 
 
    //메시지 수신시 호출
    @Override
    public void onMessageReceived(String s, Bundle bundle) {
        //메시지 수신 후 알림 띄우기
        if( bundle != null ) {
            Log.d(TAG, "onMessageReceived : "+bundle.toString());
 
            String title = bundle.getString(GCM_DATA_KEY_TITLE , "");
            String body = bundle.getString(GCM_DATA_KEY_BODY , "");
            sendNotificaion(title , body);
        }
    }
 
    //알림에 띄우기
    public void sendNotificaion(String title, String body) {
        NotificationManager notiManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
 
        String chGroupId = getString(R.string.alarm_ch_group_id_gcm);
        String channelId = getString(R.string.alarm_ch_id_gcm);
        //26 오레오 이상
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if!checkNotificationChannelGroup(chGroupId) ) {
                //알림 채널 그룹
                NotificationChannelGroup notiGroup = new NotificationChannelGroup( chGroupId, getString(R.string.alarm_ch_group_name_gcm) );
                notiManager.createNotificationChannelGroup( notiGroup );
            }
 
            if!checkNotificationChannel(channelId) ) {
                //알림 채널
                NotificationChannel notiChannel = new NotificationChannel(channelId, getString(R.string.alarm_ch_name_gcm), NotificationManager.IMPORTANCE_HIGH);
                notiChannel.setGroup(chGroupId);
                notiChannel.enableLights(true);
                notiChannel.setLightColor(Color.GREEN);
                notiChannel.enableVibration(true);
                notiChannel.setVibrationPattern( ALARM_PATTERN );
                notiChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
                notiChannel.setShowBadge(true);
                notiManager.createNotificationChannel(notiChannel);
            }
        }
 
        //알림 생성
        String appName = getString(R.string.app_name);
 
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pi = PendingIntent.getActivity(this0, intent, PendingIntent.FLAG_UPDATE_CURRENT);   //이미 존재할 경우 이를 유지하고 추가 데이터만 새로운 Intent에 있는 것으로 대체
 
        NotificationCompat.Builder noti = new NotificationCompat.Builder(this, channelId);
        noti.setAutoCancel(true);   //클릭시 알림 제거
        noti.setContentTitle(title);
        noti.setContentText(body);
        noti.setTicker(appName);
        noti.setSmallIcon(R.mipmap.ic_launcher);
        noti.setContentIntent(pi);
        noti.setVibrate( ALARM_PATTERN );
        noti.setSound( RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) );
        noti.setOngoing(false);  //지우기 버튼으로 삭제 (true - 일반 알림 위에 정렬, 지우기 버튼으로 삭제 못함)
        noti.setOnlyAlertOnce(true);    //알림이 아직 표시되지 않은 경우 사운드, 진동, 티커만 재생되도록
        noti.setWhen( System.currentTimeMillis() ); //알림에서 보여지는 발생시간
        noti.setNumber(1);  //알림의 오른쪽 번호
        noti.setGroupSummary(true);
 
        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
            noti.setVisibility( Notification.VISIBILITY_SECRET );   //보안화면에서 알림 보이지 않음
        }
 
        try {
            notiManager.notify(NOTIFICATION_ID++ , noti.build() );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    //notification channel group 등록 체크
    public boolean checkNotificationChannelGroup(String groupId) {
        boolean result = false//true : 이미 등록됨 , false : 미등록
 
        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
            NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            List<NotificationChannelGroup> groups = notificationManager.getNotificationChannelGroups();
 
            if( groups != null && groups.size() > 0 ) {
                for ( NotificationChannelGroup group : groups ) {
                    if( groupId.equalsIgnoreCase(group.getId()) ) {
                        result = true;
                        break;
                    }
                }
            }
        }
 
        return result;
    }
 
    //notification channel 등록 체크
    public boolean checkNotificationChannel( String channelId ) {
        if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
            NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            return notificationManager.getNotificationChannel(channelId) != null ? true : false;
        }
 
        return false;
    }
}
 
cs

* GCM 메시지를 수신한 후 알림을 띄웁니다

* GCM 메시지 수신이 되면 onMessageReceived 함수가 호출됩니다

 

 

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        getGcmToken();
    }
 
    //token 가져오기
    public void getGcmToken(){
        SharedPreferences pref = getSharedPreferences(getString(R.string.pref_gcm_token) , Context.MODE_PRIVATE);
        String token = pref.getString(getString(R.string.pref_key_gcm_token), "");
 
        if( TextUtils.isEmpty(token) ) {
            Intent intent = new Intent( this, RegistrationIntentService.class );
            startService( intent );
        }
        else {
            Log.d("GCM_Token", token);
        }
    }
}
cs

* MainActivity 시작시 GCM 토큰이 없으면 GCM 토큰을 가져오는 서비스를 시작합니다

BarcodeScanner.zip


Google의 Mobile Vision을 이용한 바코드 스캐너 만들기



레퍼런스 : https://developers.google.com/android/reference/com/google/android/gms/vision/package-summary

샘플 : https://github.com/googlesamples/android-vision/tree/master/visionSamples/barcode-reader

 

* 샘플에 나와있는 소스를 기반으로 작업하지만 일부는 커스텀을 합니다

android.hardware.Camera가 21부터 deprecated 되었지만 샘플에서 사용하므로 그대로 사용합니다

 

 

build.gradle
1
2
3
4
5
dependencies {
    ...
 
    implementation 'com.google.android.gms:play-services-vision:9.8.0'
}
cs

* 구글플레이 서비스를 이용합니다 (만약 인터넷이 되지 않아 라이브러리를 다운받지 못하면 이용할 수 없습니다.)

 

 

AndroidManifest.xml

1
2
3
4
5
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.CAMERA" />
 
    <uses-feature android:name="android.hardware.camera" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
cs

* 카메라 권한이 필요합니다

 

 

BarcodeActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package com.ghj.scanner;
 
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;
 
import com.ghj.scanner.barcode.BarcodeGraphic;
import com.ghj.scanner.barcode.BarcodeGraphicTracker;
import com.ghj.scanner.barcode.BarcodeTrackerFactory;
import com.ghj.scanner.barcode.CameraSource;
import com.ghj.scanner.barcode.CameraSourcePreview;
import com.ghj.scanner.barcode.GraphicOverlay;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
 
import java.io.IOException;
 
public class BarcodeActivity extends AppCompatActivity implements BarcodeGraphicTracker.BarcodeUpdateListener {
 
    //permission
    final private int PERM_REQUEST_CAMERA = 1000;
 
    //ui
    private CameraSource mCameraSource;
    private CameraSourcePreview mPreview;
    private GraphicOverlay<BarcodeGraphic> mGraphicOverlay;
    private FrameLayout boxBarcodeScan;
 
    //상수
    final private String MSG_FAIL_PERM = "카메라 권한이 없습니다";
    final private String MSG_FAIL_LIB = "라이브러리 구동에 실패했습니다";
    final private String MSG_FAIL_CAMERA = "카메라 열기에 실패했습니다";
    final private long[] VIBRATE_PATTERN = { 0701040 };    //진동패턴
 
    //플래그
    private boolean isFail = false//실패여부
    private boolean mBarcodeGrant = false;
 
    //진동
    Vibrator vibrator;
 
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView( R.layout.activity_barcode );
 
        mPreview = (CameraSourcePreview)findViewById(R.id.preview);
        mGraphicOverlay = (GraphicOverlay<BarcodeGraphic>)findViewById(R.id.graphicOverlay);
        boxBarcodeScan = (FrameLayout)findViewById(R.id.boxBarcodeScan);
 
        checkPermission();
        if( mBarcodeGrant ) {
            startBarcode();
        }
 
        vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
    }
 
    @Override
    protected void onResume() {
        super.onResume();
 
        if!isFail ) {
            checkPermission();
 
            if( mBarcodeGrant ) {
                restartPreview();
            }
            else {
                requestPermission();
            }
        }
    }
 
    @Override
    protected void onPause() {
        super.onPause();
 
        if( mPreview != null ) {
            mPreview.stop();
        }
    }
 
    @Override
    protected void onDestroy() {
        onFinish();
 
        super.onDestroy();
    }
 
    //권한 체크
    public void checkPermission() {
        if(Build.VERSION.SDK_INT > 22) {
            if( ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ) {
                mBarcodeGrant = false;
                return;
            }
        }
        mBarcodeGrant = true;
    }
 
    //권한 요청
    public void requestPermission() {
        if(Build.VERSION.SDK_INT > 22) {
            String[] perm = new String[]{Manifest.permission.CAMERA};
            requestPermissions(perm, PERM_REQUEST_CAMERA);
        }
    }
 
    //구글플레이 체크
    public boolean checkGooglePlay() {
        int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getApplicationContext());
        if (code != ConnectionResult.SUCCESS) {
            return false;
        }
        return true;
    }
 
 
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if( requestCode == PERM_REQUEST_CAMERA ) {
            if( grantResults.length > 0 && grantResults[0== PackageManager.PERMISSION_GRANTED) {
                //권한획득 성공
                mBarcodeGrant = true;
                startBarcode();
            }
            else {
                onFailDialog( MSG_FAIL_PERM );
            }
        }
    }
 
    //바코드 시작
    public void startBarcode() {
        if( mBarcodeGrant ) {
            if( checkGooglePlay() ) {
                if!createCameraSource() ) {
                    //라이브러리 없음
                    onFailDialog( MSG_FAIL_LIB );
                }
            }
            else {
                //구글플레이 서비스 실패
                onFailDialog( MSG_FAIL_LIB );
            }
        }
    }
 
    //카메라 객체 생성
    private boolean createCameraSource() {
        Context context = getApplicationContext();
        boolean autoFocus = true;
        boolean useFlash = false;
 
 
        //모든 바코드 검색
        BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build();
        BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay, this);
        barcodeDetector.setProcessor(new MultiProcessor.Builder<>(barcodeFactory).build());
 
        //필요한 라이브러리를 다운받아서 사용할 수 있는지 여부
        if (!barcodeDetector.isOperational()) {
            return false;
        }
 
        CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
                .setFacing( CameraSource.CAMERA_FACING_BACK)
                .setRequestedPreviewSize(19201080)
                .setRequestedFps(15.0f)
                .setFocusMode(autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null)
                .setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null);
 
        mCameraSource = builder.build();
        return true;
    }
 
    //카메라 프리뷰
    private void restartPreview() throws SecurityException {
        if (mCameraSource != null) {
            try {
                mPreview.start(mCameraSource, mGraphicOverlay);
            } catch (IOException e) {
                e.printStackTrace();
                //카메라 열다가 실패
                onFailDialog( MSG_FAIL_CAMERA );
            }
        }
    }
 
    //바코드 인식됨
    @Override
    public void onBarcodeDetected(Barcode barcode) {
        try {
            if( Build.VERSION.SDK_INT >= 26 )
            {
                VibrationEffect vibrationEffect = VibrationEffect.createWaveform(VIBRATE_PATTERN, -1);
                vibrator.vibrate(vibrationEffect);
            }
            else
            {
                vibrator.vibrate(VIBRATE_PATTERN, -1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        final Barcode result = barcode;
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                mPreview.stop();
 
                new Handler(getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), result.displayValue, Toast.LENGTH_SHORT).show();
 
                        Intent intent = new Intent();
                        intent.putExtra( "BARCODE_NUMBER", result.displayValue);
 
                        setResult(RESULT_OK, intent);
 
                        onFinish();
                        finish();
                    }
                }, 1000);
            }
        });
    }
 
    //바코드 해제
    public void onFinish() {
        if( mPreview != null ) {
            mPreview.release();
            mPreview = null;
        }
 
        if( mCameraSource != null ) {
            mCameraSource.release();
            mCameraSource = null;
        }
    }
 
 
    //바코드 인식 실패 다이얼로그
    public void onFailDialog(String message) {
        isFail = true;
 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message)
                .setPositiveButton("확인"new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onFinish();
                        finish();
                    }
                });
        builder.show();
    }
}
 
cs

* 바코드 인식을 성공하면 화면이 멈추고 1초후 바코드 번호를 넘깁니다

* 바코드 인식을 할 수 없으면 alert가 뜨고 클릭하면 이전화면으로 이동합니다

 

 

activity_barcode.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <com.ghj.scanner.barcode.CameraSourcePreview
        android:id="@+id/preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <com.ghj.scanner.barcode.GraphicOverlay
            android:id="@+id/graphicOverlay"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </com.ghj.scanner.barcode.GraphicOverlay>
 
    </com.ghj.scanner.barcode.CameraSourcePreview>
 
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:text="바코드를 스캔하세요"
            android:textColor="#ffffff"
            android:textSize="16dp"
            android:layout_marginTop="54dp"
            android:layout_centerHorizontal="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@+id/boxBarcodeScan"
            android:layout_centerInParent="true"
            android:layout_width="@dimen/scan_area_width"
            android:layout_height="@dimen/scan_area_height" />
    </RelativeLayout>
 
</RelativeLayout>
 
 
cs

* RelativeLayout에 카메라가 보여지는 화면을 추가하고 그위에 뷰들을 올림으로써 커스텀할 수 있습니다

 

 

CameraSourcePreview.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        //카메라 프리뷰 화면을 xml에서 정한 전체화면으로 합니다
        int width = right - left;
        int height = bottom - top;
//        int width = 320;
//        int height = 240;
//        if (mCameraSource != null) {
//            Size size = mCameraSource.getPreviewSize();
//            if (size != null) {
//                width = size.getWidth();
//                height = size.getHeight();
//            }
//        }
//
//        // Swap width and height sizes when in portrait, since it will be rotated 90 degrees
//        if (isPortraitMode()) {
//            int tmp = width;
//            //noinspection SuspiciousNameCombination
//            width = height;
//            height = tmp;
//        }
        ...
    }
cs

* 저는 카메라 프리뷰를 전체화면에 그대로 보여줍니다. 비율을 변경하지 않습니다

 

 

GraphicOverlay.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    @Override
    protected void onDraw(Canvas canvas) {
 
        super.onDraw(canvas);
 
        synchronized (mLock) {
            if ((mPreviewWidth != 0&& (mPreviewHeight != 0)) {
                mWidthScaleFactor = (float) canvas.getWidth() / (float) mPreviewWidth;
                mHeightScaleFactor = (float) canvas.getHeight() / (float) mPreviewHeight;
            }
 
            for (Graphic graphic : mGraphics) {
                graphic.draw(canvas);
            }
 
            //todo 바깥의 dim 처리
            Paint paint = new Paint();
            paint.setColor(Color.parseColor("#AA000000"));
            paint.setStrokeWidth(1f);
 
            Path path = new Path();
            path.moveTo(00);
            path.lineTo(mPreviewWidth, 0);
            path.lineTo(mPreviewWidth, mPreviewHeight);
            path.lineTo(0, mPreviewHeight);
            path.lineTo(0 , 0);
 
            if( scanRect != null ) {
                path.moveTo(scanRect.left, scanRect.top);
                path.lineTo(scanRect.left, scanRect.bottom);
                path.lineTo(scanRect.right, scanRect.bottom);
                path.lineTo(scanRect.right, scanRect.top);
                path.lineTo(scanRect.left, scanRect.top);
            }
 
            canvas.drawPath(path, paint);
        }
    }
cs

* Dim처리하는 부분입니다

* activitiy_barcode.xml에서 background 속성을 이용하여 배경을  dim처리 해도 됩니다

 

 

결과

* 바코드를 스캔한 모습입니다



canvas 에서 속이 빈 도형 그리기

 

 

path를 이용하여 그려야 하는데 속이 빈 영역은 바깥영역의 반대방향으로 그려야 합니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
 
        synchronized (mLock) {
            canvas.drawARGB(255255255255);
 
            Paint paint = new Paint();
            paint.setColor(Color.parseColor("#0000FF"));
            paint.setStrokeWidth(1f);
 
            Path path = new Path();
            path.moveTo(00);  //시작
            path.lineTo(10800);
            path.lineTo(10801920);
            path.lineTo(01920);
            path.lineTo(0 , 0); //끝은 시작지점으로 돌아옵니다
 
            //이전 path와 역방향으로 그린다
            path.moveTo(200400);
            path.lineTo(200600);
            path.lineTo(900600);
            path.lineTo(900400);
            path.lineTo(200400);
            canvas.drawPath(path, paint);
        }
    }
cs

 

 

결과

* 파란색 사각형안에 속이 빈 사각형때문에 하얀색 배경이 보이고 있습니다


main.zip

 

액티비티를 팝업(Popup)으로 띄우기 , 데이터 주고받기

 

 

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class MainActivity extends AppCompatActivity {
 
    TextView txtResult;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        txtResult = (TextView)findViewById(R.id.txtResult);
    }
 
    //버튼
    public void mOnPopupClick(View v){
        //데이터 담아서 팝업(액티비티) 호출
        Intent intent = new Intent(this, PopupActivity.class);
        intent.putExtra("data""Test Popup");
        startActivityForResult(intent, 1);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==1){
            if(resultCode==RESULT_OK){
                //데이터 받기
                String result = data.getStringExtra("result");
                txtResult.setText(result);
            }
        }
    }
}

cs

 
 

PopupActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class PopupActivity extends Activity {
 
    TextView txtText;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //타이틀바 없애기
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.popup_activity);
 
        //UI 객체생성
        txtText = (TextView)findViewById(R.id.txtText);
 
        //데이터 가져오기
        Intent intent = getIntent();
        String data = intent.getStringExtra("data");
        txtText.setText(data);
    }
 
    //확인 버튼 클릭
    public void mOnClose(View v){
        //데이터 전달하기
        Intent intent = new Intent();
        intent.putExtra("result""Close Popup");
        setResult(RESULT_OK, intent);
 
        //액티비티(팝업) 닫기
        finish();
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //바깥레이어 클릭시 안닫히게
        if(event.getAction()==MotionEvent.ACTION_OUTSIDE){
            return false;
        }
        return true;
    }
 
    @Override
    public void onBackPressed() {
        //안드로이드 백버튼 막기
        return;
    }
}
cs

* 10 : 타이틀바 없애기

* 17-18 : Intent 에서 data 가져오기

* 25-27 : Intent로 data 전달하기

* 34-40 : 바깥 레이어를 눌러도 닫히지 않게 하기

* 43-46 : 안드로이드 백버튼 막기

 

 

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="16dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:paddingBottom="8dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="액티비티를 팝업으로 띄우기"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
 
    <LinearLayout
        android:paddingBottom="8dp"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:text="팝업"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="mOnPopupClick"/>
    </LinearLayout>
 
    <LinearLayout
        android:paddingBottom="8dp"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/txtResult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
 
</LinearLayout>
 
cs

 

 

popup_activity.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#eeeeee"
    android:orientation="vertical"
    android:layout_width="300dp"
    android:layout_height="wrap_content">
 
    <!-- 타이틀바 -->
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="Notice"
            android:textSize="20sp"
            android:textColor="#fff"
            android:gravity="center"
            android:background="#ff7a00"
            android:layout_width="match_parent"
            android:layout_height="53dp" />
    </LinearLayout>
    <!-- //end 타이틀바 -->
 
    <!-- Notice -->
    <LinearLayout
        android:padding="24dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/txtText"
            android:textSize="15sp"
            android:textColor="#000"
            android:alpha="0.87"
            android:gravity="center"
            android:layout_marginBottom="3dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <!-- Notice -->
 
    <View
        android:background="#66bdbdbd"
        android:layout_width="match_parent"
        android:layout_height="1dp" />
 
    <!-- 닫기 버튼 -->
    <LinearLayout
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:text="확인"
            android:textSize="15sp"
            android:textColor="#ff7a00"
            android:padding="16dp"
            android:gravity="center"
            android:background="#00000000"
            android:layout_width="match_parent"
            android:layout_height="53dp"
            android:onClick="mOnClose"/>
    </LinearLayout>
    <!--// 닫기 버튼 -->
</LinearLayout>
cs

팝업의 가로세로 길이는 직접 정해줍니다

 

 

AndroidMenifest.xml

1
2
        <!-- 팝업 Activity -->
        <activity android:name=".PopupActivity" android:theme="@android:style/Theme.Dialog" />
cs

* Popup으로 띄울 Activity의 Theme를 바꿔줍니다

 

 

결과

* 팝업 호출(데이터 전달) -> 팝업에서 전달받은 데이터 보여줌 , 팝업 닫기(데이터 전달) -> 데이터 받아서 보여줌

 



백버튼 두번 눌러 앱종료하기


 

2초 이내에 백버튼을 2번 누르면 앱이 종료된다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    //앱종료시간체크
    long backKeyPressedTime;    //앱종료 위한 백버튼 누른시간    
    ...
 
    //뒤로가기 2번하면 앱종료
    @Override
    public void onBackPressed() {
        //1번째 백버튼 클릭
        if(System.currentTimeMillis()>backKeyPressedTime+2000){
            backKeyPressedTime = System.currentTimeMillis();
            Toast.makeText(this, getString(R.string.APP_CLOSE_BACK_BUTTON), Toast.LENGTH_SHORT).show();
        }
        //2번째 백버튼 클릭 (종료)
        else{
            AppFinish();
        }
    }
 
    //앱종료
    public void AppFinish(){
        finish();
        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
cs

 

* 첫번째 백버튼을 누른 시간을 변수에 넣은 후 2000초 이내에 두번째 백버튼을 클릭했는지 체크하여 2초이내에 2번 백버튼을 눌렀으면 앱을 종료합니다

No static field xxx of type I in class Lcom/xxx/xxx/xxx/R$id



기존에 작업하던 xml 파일을 다른 모듈에 붙여 넣은 후 그 화면으로 진입하니 Runtime 중에 다음과 같은 에러가 나왔습니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
java.lang.NoSuchFieldError: No static field xxx of type I in class Lcom/xxx/xxx/xxx/R$id; 
or its superclasses (declaration of 'xxx.xxx.xxx.xxx.R$id' appears in /data/app/xxx/xxx.apk)
        at xxx.xxx.xxx.xxx.activity.OcrActivity.setPreviewLayout(OcrActivity.java:177)
        at xxx.xxx.xxx.xxx.activity.OcrActivity.startOcr(OcrActivity.java:156)
        at xxx.xxx.xxx.xxx.activity.OcrActivity.onCreate(OcrActivity.java:70)
        at android.app.Activity.performCreate(Activity.java:6904)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7325)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
cs

 

원인

다른 모듈에서 제가 사용하는 layout 파일과 동일한 이름의 파일이 있었기 때문입니다

제가 setContentView() 에서 사용하는 layout 파일은 다른 파일이었고 그 파일에는 제가 사용하고자 하는 id가 없었습니다

R.java 파일에 제가 사용하고자 하는 id가 없다는 에러메시지 입니다

 

해결

동일한 layout 파일을 삭제하거나 이름을 변경합니다

R.java 파일의 경로가 작업하는 모듈의 경로와 같은지 확인합니다

+ Recent posts