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처리 해도 됩니다

 

 

결과

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



+ Recent posts