Skip to main content
조회 수 28991 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄


이제 또 필요한 기능이 푸쉬~ 기능인데요... (내부 notification 말구요... 외부에서 푸쉬하는거^^)


https://github.com/phonegap-build/PushPlugin 라는 곳이 있네요~


cordova plugin add https://github.com/phonegap-build/PushPlugin.git

라고 치고... 적용하면 될것 같은데... 역시 오류를 뿜네요~

 

오류에 대한 해결책은... https://github.com/phonegap-build/PushPlugin/pull/39 여기서 수정하라는 데로 모두 수정하시고,

cordova plugin add https://github.com/phonegap-build/PushPlugin.git -d

옵션값 -d 를 주시고 플러그인 추가 하면 정상적으로 적용이 됩니다.


정상적이라면... src 폴더, config.xml, AndroidManifest.xml 파일, libs 폴더에 자동으로 파일 추가 및 수정이 되어 있을 겁니다.

(cordova 3.0 부터 이렇게 자동으로 수정해 주는건지... 아주 편리하고 좋습니다^^)

 

근데 assets\www 폴더에 PushNotification.js 파일이 없으므로, 잘 찾아서 copy만 해주시면 됩니다.

여기까지 세팅끝!

 

 

지금부터 PushNotification을 웹사이트에 심는 절차 입니다. (심는다는 표현이 ㅎㅎ)

기본적으로 js 파일은 불러와야 겠죠?

<script type="text/javascript" charset="utf-8" src="PushNotification.js"></script>

 

https://github.com/phonegap-build/PushPlugin 페이지에 Plugin API 부분 부터 script 태그 사이에 넣어 줍니다.

<script type="text/javascript" charset="utf-8">

    넣어주세용~

</script>

 

그럼 전체적으로 아래와 같은 소스가 됩니다.

자세히 보니 $. 쓰더라구요~ 그럼 jquery 불러온다고 말을 해줘야 하는데... 쯧쯧... 아무튼 눈치것 저는 추가했습니다.

그리고 device.platform 이라는 것도 보이는데... 이건 phonegap API Device 잖아~~~ 우뛰~

눈치것 c:\hello>cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git

설치해 줍니다. 그냥 명령어만 치면 해줄게 없는줄 알았더니...
AndroidManifest.xml 파일에 <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 한줄을 추가해 줘야 합니다. 우뛰~ 왜~ 자동으로 안들어가지남~ 우뛰~ (제가 너무 거져 먹을려고 한건지...)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Notification Example</title>

    <script type="text/javascript" charset="utf-8" src="jquery.js"></script> 
    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8" src="PushNotification.js"></script>
    <script type="text/javascript" charset="utf-8">
	    document.addEventListener("deviceready", onDeviceReady, false);
	 
		function onDeviceReady() {
			var pushNotification;
			pushNotification = window.plugins.pushNotification; 
	
			if (device.platform == 'android' || device.platform == 'Android') {
			    pushNotification.register(successHandler, errorHandler,{"senderID":"본인의Project Number입력","ecb":"onNotificationGCM"});
			} else {
			    pushNotification.register(tokenHandler, errorHandler,{"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});
			}		
		
		    $("#app-status-ul").append('<li>deviceready event received</li>');
		
		    document.addEventListener("backbutton", function(e)
		    {
		        $("#app-status-ul").append('<li>backbutton event received</li>');
		
		        if( $("#home").length > 0)
		        {
		            e.preventDefault();
		            pushNotification.unregister(successHandler, errorHandler);
		            navigator.app.exitApp();
		        }
		        else
		        {
		            navigator.app.backHistory();
		        }
		    }, false);
		
		    // aditional onDeviceReady work…
		}
		
		// result contains any message sent from the plugin call
		function successHandler (result) {
		    alert('result = '+result);
			//$("#app-status-ul").append('<li>result = '+result+'</li>');
		}
			
		// result contains any error description text returned from the plugin call
		function errorHandler (error) {
		    alert('error = '+error);
			//$("#app-status-ul").append('<li>error = '+error+'</li>');
		}
				
		function tokenHandler (result) {
		    // Your iOS push server needs to know the token before it can push to this device
		    // here is where you might want to send it the token for later use.
		    alert('device token = '+result);
		    //$("#app-status-ul").append('<li>device token = '+result+'</li>');
		}
 
		// iOS
		function onNotificationAPN(event) {
		    if (event.alert) {
		        navigator.notification.alert(event.alert);
		    }
		
		    if (event.sound) {
		        var snd = new Media(event.sound);
		        snd.play();
		    }
		
		    if (event.badge) {
		        pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
		    }
		}
		
		
		// Android
        function onNotificationGCM(e) {
            $("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');

            switch( e.event )
            {
                case 'registered':
                if ( e.regid.length > 0 )
                {
                    $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
                    // Your GCM push server needs to know the regID before it can push to this device
                    // here is where you might want to send it the regID for later use.
                    console.log("regID = " + e.regID);
                }
                break;

                case 'message':
                    // if this flag is set, this notification happened while we were in the foreground.
                    // you might want to play a sound to get the user's attention, throw up a dialog, etc.
                    if (e.foreground)
                    {
                        $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');

                        // if the notification contains a soundname, play it.
                        //var my_media = new Media("/android_asset/www/"+e.soundname);
                        //my_media.play();
                    }
                    else
                    {   // otherwise we were launched because the user touched a notification in the notification tray.
                        if (e.coldstart)
                            $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
                        else
                        $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
                    }

                    $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
                    $("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
                break;

                case 'error':
                    $("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
                break;

                default:
                    $("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
                break;
            }
        }		
    </script>
  </head>
  <body>
	<div id="home">
	    <div id="app-status-div">
	        <ul id="app-status-ul">
	            <li>Cordova PushNotification Plugin Demo</li>
	        </ul>
	    </div>
	</div>
  </body>
</html>

여기까지를 클라이언트 라고 말하더군요~ 즉, 핸드폰에서 처리해야 할 부분...

여기까지 하고 앱을 구동해 보면 다음과 같은 화면이 나옵니다~ ㅎㅎ

아쉬운건 에뮬에서는 GCM 서버와 통신해서 regID 값을 불러오지 못하네요~
제 폰에서는 바로바로 되는데...

로그값에는 이런 경고문구가...
THREAD WARNING: exec() call to PushPlugin.register blocked the main thread for 92ms. Plugin should use CordovaInterface.getThreadPool().

 

제폰은 아래와 같이 나옵니다. 이렇게 나와야 정상입니다.
바로 나오는건 아니고.. 약 5초~10초 정도 지나야 나옵니다.

 

 

그 다음은 서버... 즉 메세지를 보낼곳에서 해야할 일입니다.

구글링 하면 아래와 같은 간단한 소스가 있습니다.

https://github.com/AndroidBegin/Android-Google-Cloud-Messaging-GCM-using-PHP-Tutorial

 

여기서도 보시면 Client, Server 두갈래로 나뉩니다.

위에서 코르도바 3.0 기준으로 클라이언트는 끝냈으므로, 서버쪽을 보고... php 구현을 합니다.

메세지를 전송하면 이렇게 오겠죠? ㅎㅎ

 

 

솔직히 여기까지 구현하는데... 좀 시간이 걸렸는데... 생략된 부분이 있습니다.

https://code.google.com/apis/console 접속해서...

 

Create project... 생성후에  API Access 에서 Create new Server key... 를 생성해서

 

클라이언트에서는 senderID 값을 활용하고,

서버에서는 Google API Key 와 Device Registration ID 값을 활용해야 합니다.

(무슨 소리인지... 하시겠지만, 저도 push를 구현하면서 history를 좀 찾아보고 이해를 했습니다.)

 

안드로이드는 당연히 구글과 연동될수밖에 없고... 그중에서 무료로 제공해주는 GCM 이라는 서비스가 있다는 것이요~

push server와 제가 말했던 클라이언트, 서버에서의 서버는 서로 다른겁니다.

 

여기까지 했으니... 한번도 써보지 않은 iOS쪽 구현을 해봐야 할 것 같습니다.

결국 폰갭을 사용한다는 것은 여러가지 OS에서 함께 구현하고자 했던 것이니깐요^^;

 

그럼 다시 테스트 하러 휘리릭~