Mac dnsmasq를 이용하여 DNS 서버 구축하기

* 호스트(Mac PC)와 내부망을 연결하고 와이파이를 공유하여 게이트웨이 역할을 하도록 합니다

호스트(Mac PC)에 dnsmasq 를 설치하여 DNS 서버를 구축합니다

* 그러면 단말기는 호스트(Mac PC)에 와이파이로 붙어서 도메인을 사용하여 내부망과 통신할 수 있습니다



1. Homebrew 설치하기

다음 명령어를 입력합니다

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

* 사이트 : https://brew.sh/index_ko



2. dnsmasq 설치하기

다음 명령어를 입력합니다

brew install dnsmasq

 

 

3. dnsmasq 설정하기

설정 디렉토리를 만듭니다

mkdir -pv $(brew --prefix)/etc/

* 디렉토리 경로를 알고 싶으면 다음 명령어를 입력합니다

  echo $(brew --prefix)/etc/ 


*.dev

$(brew --prefix)/etc/dnsmasq.conf 를 vi 에디터로 열어서 'address=/.dev/127.0.0.1' 를 추가합니다

 

자동

sudo cp -v $(brew --prefix dnsmasq)/homebrew.mxcl.dnsmasq.plist /Library/LaunchDaemons/

sudo launchctl load -w /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist


nameserver를 resolver에 추가

sudo mkdir -v /etc/resolver

/etc/resolver/dev 를 vi 에디터로 열어서 'nameserver 127.0.0.1' 를 추가합니다

 

dnsmasq service 재시작

sudo launchctl stop homebrew.mxcl.dnsmasq

sudo launchctl start homebrew.mxcl.dnsmasq

 

 

4. Mac의 인터넷 공유를 시작합니다.

인터넷 공유 링크 : 



5. /etc/hosts 파일에 도메인과 ip주소를 입력하고 dnsmasq 서비스를 재시작합니다

1
2
3
4
5
6
7
8
9
10
11
12
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1    localhost
255.255.255.255    broadcasthost
::1             localhost
 
 
192.168.2.1 lottodr.com
cs
 
 

6. 다른 디바이스MAC에 Wi-Fi로 붙은 후 도메인을 이용하여 접속합니다


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

 

 

결과

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


인터넷 공유를 사용하여 Mac을 AP처럼 사용하기



시스템 환경설정 > 공유 항목을 클릭합니다.

 

   

1. 인터넷 공유를 클릭합니다 (관리자 권한이 없으면 자물쇠를 클릭하여 관리자로 접속합니다)

2. 연결 공유를 랜선으로 연결된 내부망을 선택합니다

3. 다음 사용에서 Wi-Fi를 선택합니다

4. Wi-Fi 옵션을 클릭합니다

 

 

네트워크 이름(SSID), 보안, 암호를 입력하고 승인을 누릅니다

 

 

인터넷 공유의 체크박스를 선택해서 "인터넷 공유를 켜시겠습니까?" 대화상자가 나오면 시작을 눌러서 인터넷 공유를 시작합니다

 

 

와이파이 아이콘이 다음과 같이 되면 인터넷 공유가 실행되는 중입니다  



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 파일의 경로가 작업하는 모듈의 경로와 같은지 확인합니다

Program type already present: xxx.xxx.xxx.BuildConfig



모듈을 새로 만든후 빌드하니 다음과 같은 에러가 나왔습니다.


원인

두 모듈의 패키지명이 같기 때문에 발생한 에러입니다.


결과

새로만든 모듈의 AndroidManifest.xml 에서 패키지명을 달리 한후 재빌드합니다.




+ Recent posts